feat(auth): 添加完整的用户认证API项目

- 实现用户注册、登录、JWT令牌认证功能
- 集成Gin、GORM、Viper、Zap等框架
- 添加密码加密、数据库操作、中间件等完整功能
- 配置多环境支持、日志轮转、CORS处理
- 创建完整的项目结构和配置文件体系
This commit is contained in:
liumangmang
2025-12-30 18:00:42 +08:00
parent 7f4527d501
commit b010f82221
139 changed files with 2772 additions and 103 deletions

View File

@@ -0,0 +1,36 @@
package main
import (
"fmt"
"github.com/spf13/viper"
)
func main() {
// 1. 设置配置文件名和路径
viper.SetConfigName("config") // 配置文件名(不含扩展名)
viper.SetConfigType("yaml") // 配置文件类型
viper.AddConfigPath(".") // 配置文件路径
// 2. 读取配置文件
if err := viper.ReadInConfig(); err != nil {
panic(fmt.Errorf("Fatal error config file: %s", err))
}
fmt.Println("Config file loaded successfully!")
// 3. 读取单个配置项
appName := viper.GetString("app.name")
appPort := viper.GetInt("app.port")
fmt.Printf("App Name: %s\n", appName)
fmt.Printf("App Port: %d\n", appPort)
// 4. 读取嵌套配置
dbHost := viper.GetString("database.host")
dbPort := viper.GetInt("database.port")
fmt.Printf("Database: %s:%d\n", dbHost, dbPort)
// 5. 读取所有配置
allSettings := viper.AllSettings()
fmt.Printf("All settings: %v\n", allSettings)
}

View 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,
)
}

View File

@@ -0,0 +1,100 @@
// package main
//
// import (
//
// "fmt"
// "os"
//
// "github.com/spf13/viper"
//
// )
//
// func main() {
// // 方案:先设置环境变量,再设置前缀和绑定
// // 1. 先设置环境变量(模拟)
// os.Setenv("MYAPP_PORT", "9000")
// os.Setenv("MYAPP_DEBUG", "true")
// os.Setenv("MYAPP_DB_HOST", "192.168.1.100")
//
// // 2. 设置环境变量前缀
// viper.SetEnvPrefix("MYAPP")
//
// // 3. 设置默认值
// viper.SetDefault("port", 8080)
// viper.SetDefault("debug", false)
// viper.SetDefault("db.host", "localhost")
//
// // 4. 绑定环境变量 - 显式指定完整的环境变量名(不加前缀)
// viper.BindEnv("port", "MYAPP_PORT")
// viper.BindEnv("debug", "MYAPP_DEBUG")
// viper.BindEnv("db.host", "MYAPP_DB_HOST") // 直接指定完整的环境变量名
//
// // 5. 读取配置
// port := viper.GetInt("port")
// debug := viper.GetBool("debug")
// dbHost := viper.GetString("db.host")
//
// fmt.Printf("Port: %d (from env)\n", port)
// fmt.Printf("Debug: %v (from env)\n", debug)
// fmt.Printf("DB Host: %s (from env)\n", dbHost)
//
// // 6. 启用自动环境变量绑定
// viper.AutomaticEnv()
//
// // 设置自定义环境变量后获取
// os.Setenv("MYAPP_CUSTOM_KEY", "custom_value")
// // 注意AutomaticEnv 后MYAPP_CUSTOM_KEY 会映射到 custom_key
// customKey := viper.GetString("custom_key")
// fmt.Printf("Custom Key: %s\n", customKey)
//
// // 验证环境变量是否真的设置成功
// fmt.Println("\n=== 验证环境变量 ===")
// fmt.Printf("MYAPP_PORT: %s\n", os.Getenv("MYAPP_PORT"))
// fmt.Printf("MYAPP_DEBUG: %s\n", os.Getenv("MYAPP_DEBUG"))
// fmt.Printf("MYAPP_DB_HOST: %s\n", os.Getenv("MYAPP_DB_HOST"))
// }
package main
import (
"fmt"
"os"
"strings"
"github.com/spf13/viper"
)
func main() {
// 1. 设置环境变量前缀
viper.SetEnvPrefix("MYAPP") // 自动添加前缀
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
// 2. 绑定环境变量
viper.BindEnv("port") // 绑定 MYAPP_PORT
viper.BindEnv("debug") // 绑定 MYAPP_DEBUG
viper.BindEnv("db.host") // 绑定 MYAPP_DB_HOST
// 3. 设置默认值
viper.SetDefault("port", 8080)
viper.SetDefault("debug", false)
// 4. 设置环境变量(模拟)
os.Setenv("MYAPP_PORT", "9000")
os.Setenv("MYAPP_DEBUG", "true")
os.Setenv("MYAPP_DB_HOST", "192.168.1.100")
// 5. 读取配置(优先级:环境变量 > 配置文件 > 默认值)
port := viper.GetInt("port")
debug := viper.GetBool("debug")
dbHost := viper.GetString("db.host")
fmt.Printf("Port: %d (from env)\n", port)
fmt.Printf("Debug: %v (from env)\n", debug)
fmt.Printf("DB Host: %s (from env)\n", dbHost)
// 6. 自动绑定所有环境变量
viper.AutomaticEnv()
os.Setenv("MYAPP_CUSTOM_KEY", "custom_value")
customKey := viper.GetString("custom.key") // 自动转换 CUSTOM_KEY -> custom.key
fmt.Printf("Custom Key: %s\n", customKey)
}

View 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,
)
}

View File

@@ -0,0 +1,39 @@
package main
import (
"fmt"
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
)
func main() {
// 读取配置文件
viper.SetConfigName("config")
viper.SetConfigType("yaml")
viper.AddConfigPath(".")
if err := viper.ReadInConfig(); err != nil {
panic(err)
}
fmt.Println("Initial config loaded")
fmt.Printf("App Name: %s\n", viper.GetString("app.name"))
fmt.Printf("App Port: %d\n", viper.GetInt("app.port"))
// 监听配置文件变化
viper.WatchConfig()
viper.OnConfigChange(func(in fsnotify.Event) {
fmt.Println("\n--- Config file changed! ---")
fmt.Printf("Event: %s\n", in.Op.String())
fmt.Printf("File: %s\n", in.Name)
fmt.Printf("App Name: %s\n", viper.GetString("app.name"))
fmt.Printf("App Port: %d\n", viper.GetInt("app.port"))
})
fmt.Println("\nWatching for config changes... (modify config.yaml to see changes)")
fmt.Println("Press Ctrl+C to exit")
// 保持程序运行
select {}
}

View File

@@ -0,0 +1,20 @@
package main
import (
"fmt"
"github.com/spf13/viper"
)
func main() {
viper.SetConfigName("config")
viper.SetConfigType("json")
viper.AddConfigPath(".")
if err := viper.ReadInConfig(); err != nil {
panic(err)
}
fmt.Printf("App Name: %s\n", viper.GetString("app.name"))
fmt.Printf("App Port: %d\n", viper.GetInt("app.port"))
}

View File

@@ -0,0 +1,22 @@
package main
import (
"fmt"
"github.com/spf13/viper"
)
func main() {
// 直接指定完整文件路径(避免和其他 config.* 文件冲突)
viper.SetConfigFile("./myconfig.toml")
if err := viper.ReadInConfig(); err != nil {
panic(err)
}
// 打印实际读取的配置文件
fmt.Printf("Using config file: %s\n\n", viper.ConfigFileUsed())
fmt.Printf("App Name: %s\n", viper.GetString("app.name"))
fmt.Printf("App Port: %d\n", viper.GetInt("app.port"))
}

View File

@@ -0,0 +1,11 @@
app:
name: MyApp-Dev
port: 8080
debug: true
database:
host: localhost
port: 3306
username: root
password: password
dbname: dev_db

View File

@@ -0,0 +1,10 @@
{
"app": {
"name": "MyApp",
"port": 8080
},
"database": {
"host": "localhost",
"port": 3306
}
}

View File

@@ -0,0 +1,11 @@
app:
name: MyApp-Prod
port: 80
debug: false
database:
host: prod.database.com
port: 3306
username: prod_user
password: prod_password
dbname: prod_db

View File

@@ -0,0 +1,17 @@
app:
name: MangMang
version: 1.0.0
port: 9999
database:
host: localhost
port: 3306
username: root
password: password
dbname: testdb
redis:
host: localhost
port: 6379
password: ""
db: 0

View File

@@ -0,0 +1,26 @@
module go-viper-demo
go 1.22.2
require (
github.com/fsnotify/fsnotify v1.7.0 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/magiconair/properties v1.8.7 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/pelletier/go-toml/v2 v2.1.0 // indirect
github.com/sagikazarmark/locafero v0.4.0 // indirect
github.com/sagikazarmark/slog-shim v0.1.0 // indirect
github.com/sourcegraph/conc v0.3.0 // indirect
github.com/spf13/afero v1.11.0 // indirect
github.com/spf13/cast v1.6.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/spf13/viper v1.18.2 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
go.uber.org/atomic v1.9.0 // indirect
go.uber.org/multierr v1.9.0 // indirect
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect
golang.org/x/sys v0.15.0 // indirect
golang.org/x/text v0.14.0 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

View File

@@ -0,0 +1,52 @@
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY=
github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/pelletier/go-toml/v2 v2.1.0 h1:FnwAJ4oYMvbT/34k9zzHuZNrhlz48GB3/s6at6/MHO4=
github.com/pelletier/go-toml/v2 v2.1.0/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6keLGt6kNQ=
github.com/sagikazarmark/locafero v0.4.0/go.mod h1:Pe1W6UlPYUk/+wc/6KFhbORCfqzgYEpgQ3O5fPuL3H4=
github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE=
github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ=
github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo=
github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0=
github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8=
github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY=
github.com/spf13/cast v1.6.0 h1:GEiTHELF+vaR5dhz3VqZfFSzZjYbgeKDpBxQVS4GYJ0=
github.com/spf13/cast v1.6.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.18.2 h1:LUXCnvUvSM6FXAsj6nnfc8Q2tp1dIgUfY9Kc8GsSOiQ=
github.com/spf13/viper v1.18.2/go.mod h1:EKmWIqdnk5lOcmR72yw6hS+8OPYcwD0jteitLMVB+yk=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE=
go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI=
go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTVQ=
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 h1:GoHiUyI/Tp2nVkLI2mCxVkOjsbSXD66ic0XW0js0R9g=
golang.org/x/exp v0.0.0-20230905200255-921286631fa9/go.mod h1:S2oDrQGGwySpoQPVqRShND87VCbxmc6bL1Yd2oYrm6k=
golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc=
golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=
gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@@ -0,0 +1,7 @@
[app]
name = "MyApp"
port = 8080
[database]
host = "localhost"
port = 3306