2019年2月10日 星期日

如何在 Google App Engine 2.0 使用 Go 1.11 開發



來到了Go的世界感覺的到的第一件事就是什麼都好輕啊,用的資源好少啊,難怪越來越多公司和專案都移到Go 得世界。 不過並不是輕和快就能輕易讓我們轉換語言,必須還得考量上手的速度以及相關library的支援度,好在Go 的社群也還算蓬勃發展,所以該有的library 都有人開發,唯一要注意的就是不像Java 有許多 Apache 這種大型社群 support的專案,go 的library 專案大多是個人開發,所以這些專案的熱門度,和維修狀態就需要格外的注意。






今天的重點在於如何升級到 Google App Engine 2.0 (beta)


緣起


為什麼要升級到 2.0 呢?主要的原因是從2.0開始支援 Go module (Go 1.11+版本),這大大簡化了開發路徑與依賴管理的麻煩,所以一開始學go 就可以直接使用go module 是幸福的。 不過因為 1.11 版本還很新,所以在許多地方可能會遇到麻煩,例如 GAE 的環境。GAE 2.0 版本以後才能執行 Go 1.11以後的版本,但是有許多GAE的API(如 Search API)都還沒支援GAE 2.0的環境,根據官方文件

The reason for this is because the App Engine Search API currently is only available in the Python2.7, Java 8 and Go 1.9 runtimes (and only in App Engine Standard)

因此需要一些 workaround,參考:
     

初始化專案


整個專案的Layout 還是依照 go 1.11 的開發環境,只是有些需要初始化的地方仍必須依照Go1.9版本以前的範例程式撰寫,請看main.go 主要有兩點差異:

1. 需要初始化 app engine

 

func main() {

 registerHandlers()
 // For Go1.9 runtime
 appengine.Main()
}

2. 處理 url 的方法

 

    // For Go1.9 runtime
    // [START request_logging]
    // Delegate all of the HTTP routing and serving to the gorilla/mux router.
    // Log all requests using the standard Apache format.
    http.Handle("/", handlers.CombinedLoggingHandler(os.Stderr, router))
    // [END request_logging]

    // For Go1.11 runtime
    //  port := os.Getenv("PORT")
    //  if port == "" {
    // port = "8080"
    // log.Printf("Defaulting to port %s", port)
    //  }
    //  log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), router)) 
 
 

取得 context 的方法

 

根據我的實驗,如果要使用GAE1.0 的API 必須使用 app engine api 取得的 context,而不能直接從 http.Request 取得。
func getContext(req *http.Request) context.Context {

    //For Go1.9
    ctx := appengine.NewContext(req)
    //For Go1.11
    //ctx:=req.Context()
    return ctx
} 
 

使用log 的方法

 

    //For Go1.9
    log.Infof(ctx, "%v", msg)
 

只要這幾點都有遵守,就可以開心的在GAE 2.0 的環境,執行和使用GAE1.0 的API

更多內容,可以參考我github 的範例專案:
https://github.com/howie/go11x-gae-project-template




沒有留言 :