Environment variables specified on app.yaml but it's not fetching on main.go

前端 未结 2 618
孤城傲影
孤城傲影 2021-01-24 03:34

I\'ve specified my environment variables in app.yaml and it\'s being fetched when I\'m running it on my local machine but once I have it deployed - it\'s not fetching it.

相关标签:
2条回答
  • 2021-01-24 03:39

    The answer icza provided worked for me. In addition, I put the once.Do() call in a handler for the /_ah/start method so that it would be called immediately when GAE started up my application.

    0 讨论(0)
  • 2021-01-24 03:40

    It is undocumented in the official doc: Defining environment variables, but environment variables defined in app.yaml in production are not set before init() functions are called. They are only set before serving the first request.

    This issue was reported here. Quoting an AppEngine engineer's answer:

    Right. Due to the nature of the implementation, environment variables are not available in your init functions, unfortunately. Although they are not tied to requests, they are not set until after all the init functions have already run, but are set before the first request is handled.

    As a result, you could use a sync.DoOnce in your main handler to perform any actions required based on the value of an environment variable since it will be properly set by that time.

    Example of achieving this with Once.Do():

    var once = sync.Once{}
    
    func MainHandler(w http.ResponseWriter, r *http.Request) {
        once.Do(mysetup)
        // do your regular stuff here
    }
    
    func mysetup() {
        // This function is executed only once. Read / use env vars here.
        var1 := os.Getenv("ENVIRONMENT_VAR1")
        _ = var1 // use var1
    }
    
    0 讨论(0)
提交回复
热议问题