[英]Google App Engine ModuleHostname: not an App Engine context
我正在尝试在 App Engine 上发现其他已部署的服务。 类似这篇文章的建议。
这是我的代码的样子:
import (
"fmt"
"net/http"
"google.golang.org/appengine"
)
func ServiceHostname(serviceName string, r *http.Request) (string, error) {
ctx := appengine.NewContext(r)
hostname, err := appengine.ModuleHostname(ctx, serviceName, "", "")
if err != nil {
return "", fmt.Errorf("unable to find service %s: %v", serviceName, err)
}
return hostname, nil
}
我在常规的 http 处理程序中调用此函数。 我遇到的错误是: not an App Engine context
。
我的代码与参考文章之间的唯一区别在于 App Engine Go 版本。 我在他使用go1
运行时的地方使用新的go111
。
你知道如何克服这个问题吗?
我找到了解决方案。 您需要在主文件中调用appengine.Main()
,即使在新的go111
运行时中不需要这样做。
所以有问题的代码保持不变,你需要像在go1.9
运行时一样注册你的处理程序。
func main() {
http.HandleFunc("/serveurl", handle)
appengine.Main()
}
来源: https ://groups.google.com/d/msg/google-appengine-go/ZcASFMWJKpE/7iwGirNiBgAJ
在Writing a main package中也提到了它:
- 或者,如果您的服务使用的是
google.golang.org/appengine
包,请包含对appengine.Main()
的调用。
您引用的文章是在考虑第一代标准环境的情况下编写的,当时尚未发布第二代(go111):
2018 年 10 月 10 日
Go运行时笔记
App Engine 标准环境的Go 1.11 运行时现在处于测试阶段。 提供了将应用程序从 Go 1.9 迁移到 Go 1.11的迁移指南。
两代人之间的差异是显着的(对于所有语言,不仅是 go)。 在迁移指南的从 App Engine Go SDK 迁移(可选)部分,我注意到:
- 使用
request.Context()
或您首选的上下文,而不是使用appengine.NewContext
。
这可能与您的错误有关。 但我实际上不是 go 用户,这只是一个理论:)
据我了解,当您的 AppEngine 应用程序将运行时设置为 go111 并且应用程序导入任何“google.golang.org/appengine”包(如日志、urlfetch、memcache 等)但应用程序没有导入时,会返回此错误调用“appengine.Main”方法。
因此,您可以选择以下任一实现:
import (
"fmt"
"net/http"
"google.golang.org/appengine"
)
func init() {
// register handlers
http.HandleFunc(“/“, indexHandler)
appengine.Main()
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
ctx := appengine.NewContext(r)
.......handle the request.......
}
func ServiceHostname(serviceName string, r *http.Request) (string, error) {
ctx := appengine.NewContext(r)
hostname, err := appengine.ModuleHostname(ctx, serviceName, "", "")
if err != nil {
return "", fmt.Errorf("unable to find service %s: %v", serviceName, err)
}
return hostname, nil
}
或者放弃所有的应用引擎包:
import (
"fmt"
“log”
"net/http"
“os”
)
func main() {
port := os.Getenv(“PORT”)
if port == “” {
port = “8080”
}
http.HandleFunc(“/“, indexHandler)
log.Fatal(http.ListenAndServe(“:”+port, Nil)
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
.....handle request....
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.