feat(auth): 添加完整的用户认证API项目
- 实现用户注册、登录、JWT令牌认证功能 - 集成Gin、GORM、Viper、Zap等框架 - 添加密码加密、数据库操作、中间件等完整功能 - 配置多环境支持、日志轮转、CORS处理 - 创建完整的项目结构和配置文件体系
This commit is contained in:
67
Web开发/04go-viper-demo/04viper_multi_env.go
Normal file
67
Web开发/04go-viper-demo/04viper_multi_env.go
Normal file
@@ -0,0 +1,67 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/spf13/viper"
|
||||
"os"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
App struct {
|
||||
Name string `mapstructure:"name"`
|
||||
Port int `mapstructure:"port"`
|
||||
Debug bool `mapstructure:"debug"`
|
||||
} `mapstructure:"app"`
|
||||
Database struct {
|
||||
Host string `mapstructure:"host"`
|
||||
Port int `mapstructure:"port"`
|
||||
Username string `mapstructure:"username"`
|
||||
Password string `mapstructure:"password"`
|
||||
DBName string `mapstructure:"dbname"`
|
||||
} `mapstructure:"database"`
|
||||
}
|
||||
|
||||
func LoadConfig(env string) (*Config, error) {
|
||||
// 根据环境加载配置文件
|
||||
configName := fmt.Sprintf("config.%s", env)
|
||||
|
||||
viper.SetConfigName(configName)
|
||||
viper.SetConfigType("yaml")
|
||||
viper.AddConfigPath(".")
|
||||
|
||||
if err := viper.ReadInConfig(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var config Config
|
||||
if err := viper.Unmarshal(&config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &config, nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
// 从环境变量读取环境名称
|
||||
env := os.Getenv("APP_ENV")
|
||||
if env == "" {
|
||||
env = "dev" // 默认开发环境
|
||||
}
|
||||
|
||||
fmt.Printf("Loading config for environment: %s\n", env)
|
||||
|
||||
config, err := LoadConfig(env)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
fmt.Printf("App: %s\n", config.App.Name)
|
||||
fmt.Printf("Port: %d\n", config.App.Port)
|
||||
fmt.Printf("Debug: %v\n", config.App.Debug)
|
||||
fmt.Printf("Database: %s@%s:%d/%s\n",
|
||||
config.Database.Username,
|
||||
config.Database.Host,
|
||||
config.Database.Port,
|
||||
config.Database.DBName,
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user