dsfdsf8888 2015-10-26 00:49
浏览 118
已采纳

在app.yaml上指定但未在main.go上获取的环境变量

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.

Here's how I've set it up:

application: some-application
version: 1
runtime: go
api_version: go1
threadsafe: true

handlers: 
- url: /.*
  script: main.go
  secure: always

env_variables: 
  ENVIRONMENT_VAR1: 'some key'
  ENVIRONMENT_VAR2: 'some key'
  ENVIRONMENT_VAR3: 'some key'

And I'm using os.Getenv("ENVIRONMENT_VAR1") to retrieve the key and it works when I run it on my local but fails to work when deployed on google app engine.

  • 写回答

2条回答 默认 最新

  • duande1146 2015-10-27 06:23
    关注

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体