2--引入并解析YAML配置文件

在 Go 语言生态中,引入和解析 YAML 配置文件最主流、最好用的库是 spf13/viper。它不仅支持 YAML,还支持 JSON、TOML 等多种格式,并且能很方便地把配置映射到 Go 的结构体(Struct)中,提供给全项目使用。

一. 配置Viper依赖包

打开终端,在项目根目录下(即 ...\Secgo-Mall\)运行以下命令来安装 viper

go get -u github.com/spf13/viper

二. 创建 YAML 配置文件

我们在 config 目录下创建一个 config.yaml 文件,先把项目最基础的 Server 配置(如端口、运行模式)放进去。

 server:  
 # 服务运行端口   
 port: 8080  
 # 运行模式: debug 或 release  
 mode: "debug"

三. 编写配置读取代码(Config 包)

为了让整个项目都能随时随地读取到配置,我们需要写一个独立的 config 包。利用 Viper,我们把 YAML 里的内容解析到强类型的 Go Struct 中。这样在使用时可以通过代码提示直接点出来,非常安全且高效。

在 config/ 下创建 config.go`:

package config

import (
	"log"

	"github.com/spf13/viper"
)

// ServerConfig 映射 yaml 文件中的 server 部分
type ServerConfig struct {
	Port int    `mapstructure:"port"`
	Mode string `mapstructure:"mode"`
}

// Config 是整个项目的配置树
type Config struct {
	Server ServerConfig `mapstructure:"server"`
}

// GlobalConfig 定义一个全局变量,供其他包直接使用
var GlobalConfig *Config

// InitConfig 初始化 Viper 并解析配置文件
func InitConfig() {
	viper.SetConfigFile("config/config.yaml") // 指定配置文件路径
	viper.SetConfigType("yaml")                // 指定配置文件类型

	if err := viper.ReadInConfig(); err != nil {
		log.Fatalf("Error reading config file: %v", err)
	}

	if err := viper.Unmarshal(&GlobalConfig); err != nil {
		log.Fatalf("Unable to decode into struct: %v", err)
	}
}

第四. 修改 main.go 接入配置

现在回到我们的启动入口,调用刚才写好的 config.InitConfig(),并将原本写死在代码里的 :8080 替换为从配置文件读取。这里把原先 massage 的拼写小错误修正为 message

package main

import (
	"fmt"
	"log"

	"github.com/Chuan81/secgo-mall/pkg/config"
	"github.com/gin-gonic/gin"
)

func main() {
	// 初始化配置
	config.InitConfig()

	// 设置 Gin 的运行模式(debug/release)
	gin.SetMode(config.GlobalConfig.Server.Mode)

	// 创建一个带默认中间件(Logger 和 Recovery) 的路由器
	r := gin.Default()

	// 注册一个健康检查的路由,用来测试服务是否正常运行
	r.GET("/ping", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "pong",
			"service": "secgo-mall is up and running",
		})
	})

	addr := fmt.Sprintf(":%d", config.GlobalConfig.Server.Port)
	log.Printf("Starting Secgo-Mall server on %s\n", addr)

	// 启动服务器
	if err := r.Run(addr); err != nil {
		log.Fatalf("Failed to start server: %v", err)
	}
}

测试运行一下!

现在你的配置管理系统已经成型了。我们在项目根目录下运行服务:

go run cmd/secgo-mall/main.go

PS C:\Code\Projects\Secgo-Mall> go run cmd/secgo-mall/main.go
[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.

[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
 - using env:   export GIN_MODE=release
 - using code:  gin.SetMode(gin.ReleaseMode)

[GIN-debug] GET    /ping                     --> main.main.func1 (3 handlers)
2026/04/10 15:20:58 Starting Secgo-Mall server on :8080
[GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.
Please check https://github.com/gin-gonic/gin/blob/master/docs/doc.md#dont-trust-all-proxies for details.
[GIN-debug] Listening and serving HTTP on :8080
[GIN] 2026/04/10 - 15:21:05 | 200 |       0s |             ::1 | GET      "/ping"

你应该能看到 Gin 根据你在 config.yaml 中配置的 mode 和 port 启动了服务。如果你把 config.yaml 里的 mode 改为 "release" 再重新启动,你会发现 Gin 会变得更加安静,不再打印那么多调试日志。

这就是引入Viper使用 YAML 配置文件的基础流程。

posted @ 2026-04-17 17:25  Chuan81  阅读(30)  评论(0)    收藏  举报