Files
learn-golang/Web开发/04go-viper-demo/03viper_env.go
liumangmang b010f82221 feat(auth): 添加完整的用户认证API项目
- 实现用户注册、登录、JWT令牌认证功能
- 集成Gin、GORM、Viper、Zap等框架
- 添加密码加密、数据库操作、中间件等完整功能
- 配置多环境支持、日志轮转、CORS处理
- 创建完整的项目结构和配置文件体系
2025-12-30 18:00:42 +08:00

101 lines
2.9 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 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)
}