Google App Engine模块主机名:不是App Engine上下文

时间:2018-12-16 11:03:44

标签: google-app-engine go google-cloud-platform

我正在尝试在App Engine上发现其他已部署的服务。类似于this文章的建议。

这是我的代码的样子:

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版本。我正在使用新的go111,而他正在使用go1运行时。

您知道如何解决该问题吗?

3 个答案:

答案 0 :(得分:3)

我找到了解决方案。即使不需要在新的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()的调用。
  •   

答案 1 :(得分:1)

您所引用的文章是在考虑第一代标准环境的情况下编写的,当时第二代(go111)并不是http://git.fsl.cs.sunysb.edu/?p=wrapfs-latest.git;a=summary

  

2018年10月10日

     

运行时注意事项

     

App Engine标准环境的released是   现在处于测试阶段。提供Go 1.11 runtime的迁移指南。

两代人之间的差异是巨大的(对于所有语言,不仅是go语言)。在迁移指南的moving apps from Go 1.9 to Go 1.11部分中,我注意到:

  

可能与您的错误有关。但是我实际上不是go用户,这只是一个理论:)

答案 2 :(得分:0)

据我了解,当您的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
}

或放弃所有appengine程序包:

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....
}

相关问题