当前位置: 首页 > news >正文

Go后端配置文件教程

注:本文为博主,首次接触项目时的入门级配置实操

在 Go 后端中,使用配置文件管理参数(如数据库连接、服务端口等)是必备技能。Viper 是 Go 生态中最流行的配置管理库。支持多种配置文件、环境变量、命令行参数等,并具备热更新能力。

(热更新:无需重新启动应用,适用于小范围、高频更新)

第一目:首先安装viper

go get github.com/spf13/viper

第二目:基础使用步骤(附代码)

1、创建配置文件
# config.yaml
server:host: "localhost"port: 8081
database:user: "admin"password: "secret"max_connections: 100
2、初始化 Viper 并读取配置
package configimport ("github.com/fsnotify/fsnotify""github.com/spf13/viper"
)func Init() error {viper.SetConfigName("config") // 配置文件名(不含扩展名)viper.SetConfigType("yaml")   // 文件类型viper.AddConfigPath("config") // 搜索路径(当前目录)// 读取配置if err := viper.ReadInConfig(); err != nil {return err}// 监听配置变更viper.WatchConfig()viper.OnConfigChange(func(e fsnotify.Event) {println("配置已更新!新端口:", viper.GetInt("server.port"))})return nil
}
3、在代码中获取配置
package mainimport ("fmt""github.com/renhongcai/gomodule/config""github.com/spf13/viper"
)func main() {if err := config.Init(); err != nil {panic("配置初始化失败:" + err.Error())}host := viper.GetString("server.host") // 读取配置port := viper.GetInt("server.port")    // 设置端口号fmt.Printf("服务启动于:%s:%d\n", host, port)}
4、viper支持的热更新

滞塞一下程序,然后手动更改端口:

package mainimport ("fmt""github.com/renhongcai/gomodule/config""github.com/spf13/viper"
)func main() {if err := config.Init(); err != nil {panic("配置初始化失败:" + err.Error())}host := viper.GetString("server.host") // 读取配置port := viper.GetInt("server.port")    // 设置端口号for true {// 手动阻塞}fmt.Printf("服务启动于:%s:%d\n", host, port)}

更改端口号config.yaml中的 port 8081 -> 8082

打印效果:
配置已更新!新端口: 8082

第三目:进阶的一些操作

1、设置默认值
// 默认
viper.SetDefault("server.port", 3000) // 默认端口,防崩溃
2、绑定环境变量
// 自动调用
viper.AutomaticEnv()                     // 自动读取环境变量
viper.BindEnv("server.port", "APP_PORT") // 绑定 APP_PORT 到 server.port
3、映射到结构体(更推荐)

这样更安全,更省心

type ServerConfig struct {Host string `mapstructure:"host"`Port int    `mapstructure:"port"`
}

main中 

func Init(){var serverCfg ServerConfigviper.UnmarshalKey("server", &serverCfg) // 将 server 节点映射到结构体
}
4、多文件支持
viper.SetConfigFile("db.yaml")
viper.MergeInConfig() // 合并到已有配置

第四目:本篇博客的结构

.
├── config
│   ├── config.go   # Viper 初始化代码
│   └── config.yaml # 主配置文件
├── main.go         # 程序入口
└── go.mod

第五目:经验总结

路径!!路径!!路径!!非常容易配置错

若是大型项目的话,可以将配置文件按照功能,拆分成多个yaml(redis.yaml、http.yaml)

最终通过咱们上方的那个多文件支持,根据需求进行合并操作....

注:注意其优先级顺序:命令好参数 > 环境变量 > 配置文件 > 默认值)

http://www.lryc.cn/news/595924.html

相关文章:

  • Python 链接各种中间件[Mysql\redis\mssql\tdengine]
  • 发票识别技术原理
  • Redis持久化-AOF
  • Ubuntu 桌面版和服务器版在资源消耗上的对比分析
  • 第十六天(结构体初学)
  • Sa-Token大师:第四章 - 企业级架构与源码实战
  • Events
  • Linux部署.net Core 环境
  • 虚幻 5 与 3D 软件的协作:实时渲染,所见所得
  • linux-日志服务
  • 同步本地文件到服务器上的Docker容器
  • 跨维智能:全新一代人形机器人 DexForce W1 Pro
  • 大模型后训练——DPO实践
  • Mosaic数据增强介绍
  • 使用ubuntu:20.04和ubuntu:jammy构建secretflow环境
  • android模拟器手机打开本地网页
  • Tailwind CSS快速上手 Tailwind CSS的安装、配置、使用
  • J2EE模式---拦截过滤器模式
  • Vite:下一代前端构建工具的革命
  • C语言---VSCODE的C语言环境搭建
  • RISC-V基金会Datacenter SIG月会圆满举办,探讨RAS、PMU性能分析实践和经验
  • vs2017 c++ 使用sqlite3数据库
  • 末日期权的双买和单买策略区别是什么?
  • 双向链表详解及实现
  • C++_Hello算法_队列
  • 基于Java+MySQL实现(Web)文件共享管理系统(仿照百度文库)
  • 188粉福
  • Spring快速整合Mybatis
  • 技术与情感交织的一生 (十)
  • nodejs:告别全局安装,npx 命令详解及其与 npm 的区别