当前位置:网站首页>Golang根据参数引入相应配置文件的实现方式
Golang根据参数引入相应配置文件的实现方式
2022-07-01 11:53:00 【卖烤冷面的郭师傅】
1) config目录 创建dev.env和prod.env
env文件示例
dev.env
#gin
GIN_DEBUG=true
GIN_PORT=9000
prod.env
#gin
GIN_DEBUG=false
GIN_PORT=9527
2) 使用godotenv引入对应的文件
没有这个包的话需要先引入
go get github.com/joho/godotenv
package main
import (
"flag"
"log"
"os"
"github.com/gin-gonic/gin"
"github.com/joho/godotenv"
)
var envArgs string
func init() {
// 默认为dev环境
flag.StringVar(&envArgs, "env", "dev", "运行环境")
}
func main() {
// 需要先解析才能使用
flag.Parse()
err := godotenv.Load("./config/" + string(envArgs) + ".env")
if err != nil {
log.Fatal("Error loading .env file")
}
ginPort := os.GetEnv("GIN_PORT")
debugFlag := os.GetEnv("GIN_DEBUG")
if debugFlag == "true" {
gin.SetMode(gin.DebugMode)
} else {
gin.SetMode(gin.ReleaseMode)
}
r := gin.Default()
r.Run(":" + ginPort)
}
命令行执行
#prod环境
go run main.go -env=prod
#dev环境 如果env不传默认为dev
go run main.go -env=dev
边栏推荐
猜你喜欢

Mechanism and type of CPU context switch

S7-1500plc simulation

自组织是管理者和成员的双向奔赴

Seckill system 03 - redis cache and distributed lock

Shangtang entered the lifting period: the core management voluntarily banned and strengthened the company's long-term value confidence

Neo4j Chinese developer monthly - issue 202206

Redis' attack tactics

Deep understanding of grpc part1

Exposure: a white box photo post processing framework reading notes

二叉堆(一) - 原理与C实现
随机推荐
[classic example] classic list questions @ list
openinstall:微信小程序跳转H5配置业务域名教程
ACLY与代谢性疾病
kafuka学习之路(一)kafuka安装和简单使用
C knowledge point form summary 2
Matrix of numpy
Wonderful! MarkBERT
Tianrunyun, invested by Tian Suning, was listed: its market value was 2.2 billion Hong Kong, and its first year profit decreased by 75%
伸展树(一) - 概念和C实现
使用set_handler过滤掉特定的SystemC Wraning &Error Message
No statements may be issued when any streaming result sets are open and in use on a given connection
研发效能度量框架解读
Width and widthstep of iplimage
想问问,证券开户有优惠吗手机开户是安全么?
Learning summary on June 28, 2022
Kernel synchronization mechanism
C summary of knowledge points 3
Kafuka learning path (I) Kafuka installation and simple use
树莓派4B安装tensorflow2.0[通俗易懂]
耐克如何常年霸榜第一名?最新財報答案來了