Go后端配置文件教程

发布于:2025-07-23 ⋅ 阅读:(17) ⋅ 点赞:(0)

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

在 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 config

import (
	"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 main

import (
	"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 main

import (
	"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 ServerConfig
    viper.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)

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

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


网站公告

今日签到

点亮在社区的每一天
去签到