gpt4 book ai didi

google-app-engine - 在 app.yaml 上指定了环境变量,但它没有在 main.go 上获取

转载 作者:IT王子 更新时间:2023-10-29 01:59:15 27 4
gpt4 key购买 nike

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

我是这样设置的:

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") 来检索 key ,当我在本地运行它时它可以工作,但在部署到谷歌应用引擎时无法工作。

最佳答案

它在官方文档中没有记录:Defining environment variables ,但是在 app.yaml 中定义的环境变量在生产中不会在调用 init() 函数之前设置。它们仅在服务第一个请求之前设置。

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

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.

使用 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
}

关于google-app-engine - 在 app.yaml 上指定了环境变量,但它没有在 main.go 上获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33336850/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com