如何让 golang gin 与 google 应用引擎一起工作?

How to make golang gin work with google app engine?

我的GOPATH是$HOME/go,我把我项目的源码放在$HOME/go/src/myproj

并且有两个文件:

app.yaml:

application: hello
version: 1
runtime: go
api_version: go1

handlers:
- url: /.*
  script: _go_app

hello.go

package hello

import (
        "net/http"
        "github.com/gin-gonic/gin"
)

func ping(c *gin.Context) {
        c.JSON(200, gin.H{
                "message": "pong",
        })
}

func init() {
        r := gin.Default()

        api := r.Group("/api")
        {
          api.GET("/ping", ping)
        }

        http.Handle("/", r)
}

那我运行dev_appserver.py .

有效,

curl http://127.0.0.1:8080/api/ping
{"message":"pong"}

然后我决定这样拆分hello.go:

hello.go

package hello

import (
        "net/http"
        "github.com/gin-gonic/gin"
        "./api"
        // "myproj/api" // does not work too
)

func init() {
        r := gin.Default()

        api.addRoute()

        http.Handle("/", r)
}

和一个 api 文件夹,以及 api/api.go 个文件

package api

import (
        "github.com/gin-gonic/gin"
)

func ping(c *gin.Context) {
        c.JSON(200, gin.H{
                "message": "pong",
        })
}

func addRoute() {
        api := r.Group("/api")
        {
          api.GET("/ping", ping)
        }
}

然后我又 运行 dev_appserver.py . 但得到了这个错误:

ERROR 2018-09-28 05:17:47,653 instance_factory.py:229] 构建 Go 应用程序失败:(执行命令:/Users/gaco/.google-cloud-sdk/platform/google_appengine/goroot-1.9 /bin/go-app-builder -app_base /Users/gaco/go/src/myproj -api_version go1 -arch 6 -dynamic -goroot /Users/gaco/.google-cloud-sdk/platform/google_appengine/goroot-1.9 -nobuild_files ^^$ -incremental_rebuild -不安全 -print_extras_hash hello.go api/api.go)

2018/09/28 14:17:47 go-app-builder:解析输入失败:app 文件 api.go 与从 GOPATH 导入的相同文件冲突

警告 2018-09-28 05:17:47,654 instance.py:297] 无法获取实例的 PID 错误 2018-09-28 05:17:47,654 instance.py:300] '_GoBuildFailureRuntimeProxy' 对象没有属性 '_process'

问题是什么?我该如何解决?

我刚刚意识到这是我在自己的 App Engine 项目中遇到过的问题。问题是因为您的 api 文件夹嵌套在 myproject 文件夹下。 SDK 不能很好地处理导入,最终会递归导入,因此出现 2018/09/28 14:17:47 go-app-builder: Failed parsing input: app file api.go conflicts with same file imported from GOPATH 错误。

实际上,您必须确保永远不会将某些内容导入目录,这真的很烦人。

要解决此问题,根据此处的信息,您需要将其分解为更扁平的目录结构。像这样:

myproject/main // or however you want to name it
myproject/api

myproject 文件夹中没有任何内容。那就不可能递归包含了。

作为参考,我自己的项目有一个网站、api、数据库和第 3 方 api 结构,所以我的结构与您在提到的解决方案中所期望的一样。例如

project/website
project/api
project/db
project/external

请注意,我的网站和 api 都是独立的服务,因此它们在各自的目录中都有自己的 app.yaml。你只会有一个。同样在我的示例中,两个项目都导入 dbexternal.