今天被問到Go適合用在哪方面, 至今只看了Go兩個晚上的我, 實在很難回答這問題, 先從FAQ找來創立Go的目的說起:

“Go is an attempt to combine the ease of programming of an interpreted, dynamically typed language with the efficiency and safety of a statically typed, compiled language. It also aims to be modern, with support for networked and multicore computing. Finally, it is intended to be fast: it should take at most a few seconds to build a large executable on a single computer. To meet these goals required addressing a number of linguistic issues: an expressive but lightweight type system; concurrency and garbage collection; rigid dependency specification; and so on. These cannot be addressed well by libraries or tools; a new language was called for.”
簡而言之, Go的目標是一個簡單又有效率的語言, 加上一開始設計就考慮網路以及多核, 就姑且說它適合server端的開發吧

事實上, GAE(Google AppEngine)也是有支援Go的 (怎麼說呢, 好歹這也是Google自己親生的呀)

那, 現在開發server端的工具那麼多種, 有什麼樣的理由是選Go優於其他解決方案呢? 以效率來說, 或許比較好吧, 既然它是原生碼, 應該會快一些吧, 但這也沒啥好的benchmark來佐證, 劣勢呢? 以node.js來相比好了(今年看比較多這個, 直覺拿這來做比較), 它不但沒既有的developer做基礎(既有的javascript developer是很大一群的), 也沒有數量很多且快速增長的第三方模組可供利用(雖然, 盲目用npm上的模組, 某種程度上要承擔一定的風險), 最大的問題就是….“文件”

以上前半段是抱怨文, 不過文件不足也沒辦法當啥藉口, 這年頭….“做就對了”…..GAE上關於Go的文件也不是沒有, 跟著做, 就可以做出"Hello World"了, 但剛做完後, 突然楞住想….那…我的html檔案放哪裡? 我總不能每個文件都寫在程式內, 總會有靜態檔案的呀! 有點讓我回到十幾年前寫CGI的感覺

GAE的文件還真找不到, 但在Go的文件http.FileServer的範例可以找到解答, 但要把"FileServer"這個interface跟這件事聯想在一起還真有點不容易, 不過反正就是在程式內要加入下面這行來處理靜態檔案

http.Handle(“/”, http.FileServer(http.Dir(“./static”)))
這範例讓你可以把靜態檔案放在"static"目錄下, 假設你在static目錄下放一個a.html, 那這行的目的就是可以讓你用 http://your_app_host/a.html來存取它

我起始一個範例放在github上, 從這可以看完整的目錄結構, 未來相關範例也會放在這邊

via Blogger http://bit.ly/SixshC