在Go语言中,可以使用`os.Getenv(“VAR”)`来获取环境变量的值。

huangapple go评论109阅读模式
英文:

process.env.VAR alternative in Go

问题

在Go语言中,可以使用os包来访问环境变量。以下是在Go中获取单个程序提供的环境变量的示例代码:

  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. )
  6. func main() {
  7. httpPort := os.Getenv("HTTP_PORT")
  8. fmt.Println(httpPort)
  9. }

你可以使用os.Getenv()函数来获取指定环境变量的值。在上面的示例中,我们使用HTTP_PORT作为环境变量的名称,并将其打印出来。

在命令行中,你可以通过在运行程序之前设置环境变量来提供它的值。例如:

  1. $ export HTTP_PORT=5000
  2. $ go run main.go

这将在Go程序中获取到环境变量的值,并将其打印出来。

英文:

How to access the environment variable supplied to a single program in Go?

In NodeJS, I was using:

  1. const HTTP_PORT = process.env.HTTP_PORT
  1. $ HTTP_PORT=5000 node index.js

I am wondering how to get this done in Golang.

答案1

得分: 2

你可以使用os.Getenv()函数。

  1. func main() {
  2. httpPort := os.Getenv("HTTP_PORT")
  3. fmt.Printf("HTTP_PORT=%s\n", httpPort)
  4. }

在执行时:

  1. $ HTTP_PORT=5000 go run test.go
  2. HTTP_PORT=5000
英文:

You can use os.Getenv().

  1. func main() {
  2. httpPort := os.Getenv("HTTP_PORT")
  3. fmt.Printf("HTTP_PORT=%s\n", httpPort)
  4. }

While executing:

  1. $ HTTP_PORT=5000 go run test.go
  2. HTTP_PORT=5000

huangapple
  • 本文由 发表于 2021年9月5日 15:24:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/69061345.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定