douchensou6969 2017-05-03 16:02
浏览 27

AppEngine:使用与请求无关的上下文

I was trying to deploy an API using PubSub with AppEngine but I got a "not an App Engine context" error, it's related to the following code:

import (
    "golang.org/x/net/context"
    "log"

    "cloud.google.com/go/pubsub"
)

var (
    ctx                             context.Context
    pubsubClient                    *pubsub.Client
)  

func InitPubSub () {
    ctx = context.Background()

    psClient, err := pubsub.NewClient(ctx, "myproject-1234")
    if err != nil {
        log.Println("(init pub sub) error while creating new pubsub client:", err)

    } else {
        pubsubClient = psClient

    }
}

So I was looking at the BackgroundContext func from the appengine package but it says that it only works with AppEngine flexible environment (standard environment seems more appropriate to my app): https://godoc.org/google.golang.org/appengine#BackgroundContext

Do you know if there's another function I can use? Or should I create and close a client for each request?

Thanks!

  • 写回答

1条回答 默认 最新

  • dox19458 2018-06-08 17:54
    关注

    Each request should create a new client (when the client requires a context). The context of the request handles things like cancels and timeouts. So, if your request gets cancelled, you should also cancel any of the outgoing API requests. The client handles all of the outgoing API requests, so it needs the same context.

    The App Engine Standard requires requests to use the App Engine context since it handles scaling and resources automatically.

    You can get a context.Context from a request by calling appengine.NewContext(req) (g3doc).

    For example:

    import (
            "net/http"
    
            "cloud.google.com/go/pubsub"
            "google.golang.org/appengine"
            "google.golang.org/appengine/log"
    )
    
    func pubSubHandler(w http.ResponseWriter, r *http.Request) {
        ctx := appengine.NewContext(r)
        client, err := pubsub.NewClient(ctx, "myproject-1234")
        if err != nil {
            log.Errorf(ctx, "pubsub.NewClient: %v", err)
            http.Error(w, "An error occurred. Try again.", http.StatusInternalServerError)
            return
        }
        _ = client // Use the client.
    }
    

    Another note is to use the google.golang.org/appengine/log package to do logging in App Engine Standard, as done above. See Reading and Writing Application Logs.

    Building an App with Go from the official docs describes how to build an example application on App Engine Standard.

    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算