在Gin框架中,可以使用toml、json、yaml等格式的配置文件。以下是一个例子:
# server settings
[server]
port = 8080
# database settings
[database]
host = "localhost"
port = 3306
username = "root"
password = "password"
database = "mydb"
# logging settings
[logging]
level = "debug"
file = "logs/app.log"
以上配置文件中包括了三个部分:服务器设置、数据库设置和日志设置。其中,服务器设置包括端口号;数据库设置包括主机地址、端口号、用户名、密码和数据库名;日志设置包括日志级别和日志文件路径。
在代码中,可以使用github.com/BurntSushi/toml包来解析toml格式的文件,如下所示:
package main
import (
"fmt"
"github.com/BurntSushi/toml"
)
type ServerConfig struct {
Port int `toml:"port"`
}
type DatabaseConfig struct {
Host string `toml:"host"`
Port int `toml:"port"`
Username string `toml:"username"`
Password string `toml:"password"`
Database string `toml:"database"`
}
type LoggingConfig struct {
Level string `toml:"level"`
File string `toml:"file"`
}
type Config struct {
Server ServerConfig `toml:"server"`
Database DatabaseConfig `toml:"database"`
Logging LoggingConfig `toml:"logging"`
}
func main() {
var config Config
if _, err := toml.DecodeFile("config.toml", &config); err != nil {
panic(err)
}
fmt.Printf("Server port: %d\n", config.Server.Port)
fmt.Printf("Database host: %s, port: %d, username: %s, password: %s, database: %s\n",
config.Database.Host, config.Database.Port, config.Database.Username,
config.Database.Password, config.Database.Database)
fmt.Printf("Logging level: %s, file: %s\n", config.Logging.Level, config.Logging.File)
}
以上代码中,定义了三个结构体ServerConfig、DatabaseConfig和LoggingConfig来分别表示服务器设置、数据库设置和日志设置。最后定义了一个Config结构体,包含了这三个结构体。使用toml.DecodeFile()函数解析配置文件,并将结果存储在Config结构体中。最后打印出各个配置项的值。




