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

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

process.env.VAR alternative in Go

问题

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

package main

import (
	"fmt"
	"os"
)

func main() {
	httpPort := os.Getenv("HTTP_PORT")
	fmt.Println(httpPort)
}

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

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

$ export HTTP_PORT=5000
$ go run main.go

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

英文:

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

In NodeJS, I was using:

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

I am wondering how to get this done in Golang.

答案1

得分: 2

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

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

在执行时:

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

You can use os.Getenv().

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

While executing:

$ HTTP_PORT=5000 go run test.go
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:

确定