在 app.yaml 上指定的环境变量,但它没有在 main.go 上获取 [英] Environment variables specified on app.yaml but it's not fetching on main.go

查看:12
本文介绍了在 app.yaml 上指定的环境变量,但它没有在 main.go 上获取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 app.yaml 中指定了我的环境变量,当我在本地机器上运行它时会获取它,但是一旦我部署了它 - 它就不会获取它.

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.

我是这样设置的:

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'

我正在使用 os.Getenv("ENVIRONMENT_VAR1") 检索密钥,当我在本地运行它时它可以工作,但在部署在谷歌应用引擎上时无法工作.

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.

推荐答案

官方文档中没有记载:定义环境变量,但是生产中app.yaml中定义的环境变量在init()函数调用之前没有设置.它们仅在处理第一个请求之前设置.

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.

此处报告了此问题.引用 AppEngine 工程师的回答:

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

没错.不幸的是,由于实现的性质,环境变量在您的 init 函数中不可用.虽然它们不与请求绑定,但直到所有 init 函数都已运行后才设置它们,而是在处理第一个请求之前设置.

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.

因此,您可以在主处理程序中使用 sync.DoOnce 来根据环境变量的值执行所需的任何操作,因为届时它将被正确设置.

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.

使用 Once.Do() 实现此目的的示例:

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
}

这篇关于在 app.yaml 上指定的环境变量,但它没有在 main.go 上获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆