1

The Go package, google.golang.org/appengine, provides IsDevAppServer which reports whether an App Engine app is running in the development App Server (e.g. localhost:8080). However, this does not work unless the (deprecated) standalone SDK is used. See appengine.go#L57 for the implementation.

New GAE apps written in Go are basically a regular web server that can be compiled and started locally like any go program;

  • old; dev_appserver.py
  • new; go run main.go

Detecting a development server can be useful for to prevent CORS issues when running locally:

func setDevHeaders(w http.ResponseWriter) {
    w.Header().Set("Access-Control-Allow-Origin", "http://localhost:4200")
    w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
    w.Header().Set("Access-Control-Request-Method", "POST, GET")
    w.Header().Set("Access-Control-Expose-Headers", "Content-Disposition")
}

When needed I can then branch:

if appengine.IsDevAppServer() {
    setDevHeaders(w)
}

What is the recommended way to achieve this in a standalone Go server running on App Engine?

Jack
  • 10,313
  • 15
  • 75
  • 118

2 Answers2

1

The App Engine Standard Go environnement sets a number of environment variables automatically. You can have a look at the list here.

You can check if they are set and if they aren't, then your code is running locally (or at least not deployed). Or you can set the NODE_ENV environment variable to development on your machine (in your shell where you run your app locally, not in the app.yaml file) and check for its value. It'll be set to production when running on App Engine.

LundinCast
  • 9,412
  • 4
  • 36
  • 48
  • The server is not run in the App Engine Standard Go environment when started with `go run main.go` - it's just a regular web server. – Jack Jan 04 '20 at 18:06
  • Exactly. So unless you define them explicitly yourself in your local environment, these environment variables **won't** be set. So if your code tries to retrieve them and they **aren't** set, then it knows it's running in your local environment, otherwise it's been deployed and is running in App Engine. – LundinCast Jan 05 '20 at 12:38
0

It sounds tricky but I found that metadata server also respond to app engine standard.

Furthur, I used cloud.google.com/go/compute/metadata pacakge,

metadata.OnGCE()

as a quick check whether it is in my local machine or on google's machine (yeah, it returns true on app engine)

程柏硯
  • 137
  • 1
  • 10