温馨提示×

golang打包centos应用如何配置环境变量

小樊
31
2025-12-19 18:10:41
栏目: 编程语言

在Golang中,我们通常使用.env文件来配置环境变量。要在CentOS上配置环境变量,请按照以下步骤操作:

  1. 安装godotenv库,它可以帮助我们在Go程序中加载.env文件。在终端中运行以下命令:
go get github.com/joho/godotenv
  1. 在项目根目录下创建一个名为.env的文件,然后在其中添加环境变量。例如:
API_KEY=your_api_key
DATABASE_URL=mysql://user:password@localhost:3306/db_name
  1. 在Go程序中,使用godotenv库加载.env文件。在程序的入口点(通常是main.go文件)中添加以下代码:
package main

import (
	"fmt"
	"log"
	"os"

	"github.com/joho/godotenv"
)

func main() {
	err := godotenv.Load()
	if err != nil {
		log.Fatal("Error loading .env file")
	}

	apiKey := os.Getenv("API_KEY")
	databaseURL := os.Getenv("DATABASE_URL")

	fmt.Println("API Key:", apiKey)
	fmt.Println("Database URL:", databaseURL)
}
  1. 确保.env文件位于Go程序的工作目录中。当程序运行时,它将自动加载.env文件中的环境变量。

  2. 如果需要在系统级别设置环境变量,可以将它们添加到/etc/environment文件中。使用以下命令打开文件:

sudo nano /etc/environment
  1. 在文件中添加环境变量,每行一个。例如:
API_KEY=your_api_key
DATABASE_URL=mysql://user:password@localhost:3306/db_name
  1. 保存并关闭文件。要使更改生效,请重新启动系统或使用以下命令重新加载环境变量:
source /etc/environment

现在,您的Golang应用程序应该可以在CentOS上访问这些环境变量了。

0