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