go如何读取设置os的环境变量

背景

日常业务开发中,难免会遇到读取操作系统变量的场景, 如下代码片段列出了golang语言如何读取或者设置os环境变量的常用用法。仅供参考

代码

package main

import (
	"fmt"
	"os"
	"strings"
)

func main() {
    // 读取指定环境变量的值
	fmt.Println("Shell:", os.Getenv("SHELL"))

	getEnv := func(key string) {
		val, ok := os.LookupEnv(key)
		if !ok {
			fmt.Printf("%s not set\n", key)
		} else {
			fmt.Printf("%s=%s\n", key, val)
		}
	}

	getEnv("EDITOR")
	getEnv("SHELL")

	fmt.Println("before editor:", os.Getenv("EDITOR"))
	// 设置环境变量
	os.Setenv("EDITOR", "emacs")
	fmt.Println("after setenv, editor:", os.Getenv("EDITOR"))

	// os.Environ returns a copy of strings representing the environment, in the form "key=value".
	// 获取全部环境变量
	for _, e := range os.Environ() {
		pair := strings.SplitN(e, "=", 2)
		fmt.Printf("%s: %s\n", pair[0], pair[1])
	}

	// os.ExpandEnv is a helper function which replaces the $var inside a string into the value of the given variable.
	//	References to undefined variables are replaced by the empty string
	os.Setenv("EDITOR", "emacs")
    
	fmt.Println(os.ExpandEnv("My editor is $EDITOR."))
	fmt.Println(os.ExpandEnv("My shell is $SHELL."))

	// github.com/joho/godotenv  loads environment variables from the .env file
}

执行结果示例

不同机器上执行结果可能不同,此时是别人机器执行结果,示例

Shell: /bin/zsh
EDITOR not set
SHELL=/bin/zsh
before editor: 
after setenv, editor: emacs
ALACRITTY_WINDOW_ID: 0
COLORTERM: truecolor
COMMAND_MODE: unix2003
...  此处省略部分内容
SHELL: /bin/zsh
SHLVL: 1
SSH_AUTH_SOCK: /private/tmp/com.apple.launchd.XATn15hl3j/Listeners
TERM: xterm-256color
TERM_PROGRAM: Jetbrains.Fleet
TERM_PROGRAM_VERSION: 1.22.113
TMPDIR: /var/folders/ls/8nvj13l13b59rpk8c1jw_tg00000gn/T/
USER: ericyang
WINDOWID: 0
XPC_FLAGS: 0x0
XPC_SERVICE_NAME: 0
__CFBundleIdentifier: Fleet.app
__CF_USER_TEXT_ENCODING: 0x1F5:0x19:0x34
_: /usr/local/go/bin/go
EDITOR: emacs
My editor is emacs.
My shell is /bin/zsh.

你可能感兴趣的:(golang,开发语言,后端)