feat(auth): 添加完整的用户认证API项目
- 实现用户注册、登录、JWT令牌认证功能 - 集成Gin、GORM、Viper、Zap等框架 - 添加密码加密、数据库操作、中间件等完整功能 - 配置多环境支持、日志轮转、CORS处理 - 创建完整的项目结构和配置文件体系
This commit is contained in:
67
Web开发/04go-viper-demo/02viper_struct.go
Normal file
67
Web开发/04go-viper-demo/02viper_struct.go
Normal file
@@ -0,0 +1,67 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
// 配置结构体
|
||||
type Config struct {
|
||||
App AppConfig `mapstructure:"app"`
|
||||
Database DatabaseConfig `mapstructure:"database"`
|
||||
Redis RedisConfig `mapstructure:"redis"`
|
||||
}
|
||||
|
||||
type AppConfig struct {
|
||||
Name string `mapstructure:"name"`
|
||||
Version string `mapstructure:"version"`
|
||||
Port int `mapstructure:"port"`
|
||||
}
|
||||
|
||||
type DatabaseConfig struct {
|
||||
Host string `mapstructure:"host"`
|
||||
Port int `mapstructure:"port"`
|
||||
Username string `mapstructure:"username"`
|
||||
Password string `mapstructure:"password"`
|
||||
DBName string `mapstructure:"dbname"`
|
||||
}
|
||||
|
||||
type RedisConfig struct {
|
||||
Host string `mapstructure:"host"`
|
||||
Port int `mapstructure:"port"`
|
||||
Password string `mapstructure:"password"`
|
||||
DB int `mapstructure:"db"`
|
||||
}
|
||||
|
||||
func main() {
|
||||
// 读取配置文件
|
||||
viper.SetConfigName("config")
|
||||
viper.SetConfigType("yaml")
|
||||
viper.AddConfigPath(".")
|
||||
|
||||
if err := viper.ReadInConfig(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// 将配置绑定到结构体
|
||||
var config Config
|
||||
if err := viper.Unmarshal(&config); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// 使用配置
|
||||
fmt.Printf("App: %s v%s\n", config.App.Name, config.App.Version)
|
||||
fmt.Printf("Port: %d\n", config.App.Port)
|
||||
fmt.Printf("Database: %s@%s:%d/%s\n",
|
||||
config.Database.Username,
|
||||
config.Database.Host,
|
||||
config.Database.Port,
|
||||
config.Database.DBName,
|
||||
)
|
||||
fmt.Printf("Redis: %s:%d (DB %d)\n",
|
||||
config.Redis.Host,
|
||||
config.Redis.Port,
|
||||
config.Redis.DB,
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user