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

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

问题描述

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



以下是我设置它的方式:

  application:某些应用程序
版本:1
运行时:go
api_version:go1
线程安全:true

处理程序:
- url:/。 *
脚本:main.go
安全:总是

env_variables:
ENVIRONMENT_VAR1:'某个键'
ENVIRONMENT_VAR2:'某个键'
ENVIRONMENT_VAR3:'some key'

我使用 os.Getenv (ENVIRONMENT_VAR1)来检索密钥,它在我的本地上运行时工作,但在谷歌应用引擎上部署时无法工作。 解决方案

它在官方文档中是无证的:定义环境变量,但是没有设置生产中的 app.yaml 中定义的环境变量在 init()函数之前被调用。他们只在提供第一个请求前设置。



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


对。由于实现的本质,不幸的是,你的init函数中没有环境变量。
虽然它们并不与请求绑定,但是在所有初始化函数已经运行之后才设置它们,但是在处理第一个请求之前设置它们。



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




通过 Once.Do()

  var once = sync.Once {} 

func MainHandler(w http.ResponseWriter,r * http.Request){
once.Do(mysetup)
//在这里做常规的工作
}

func mysetup(){
//这个函数只执行一次。在这里阅读/使用env vars。
var1:= os.Getenv(ENVIRONMENT_VAR1)
_ = var1 // use var1
}


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.

解决方案

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
}

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

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