fix(api): 修正用户ID获取及JWT配置类型

- 修改用户ID从gin.Context获取方式,避免类型错误
- 将用户ID断言为uint类型以保证数据库查询和更新操作正确
- 修正JWT配置中的Secret类型由int改为string
- 修复路由中UpdateProfile的绑定,去除多余传参
- 代码格式调整,增加环境变量键替换支持,提升配置灵活性
This commit is contained in:
liumangmang
2025-12-30 18:01:53 +08:00
parent 67c0cbf0d7
commit 04a960ded4
2 changed files with 22 additions and 16 deletions

View File

@@ -260,6 +260,7 @@ import (
func main() {
// 1. 设置环境变量前缀
viper.SetEnvPrefix("MYAPP") // 自动添加前缀
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
// 2. 绑定环境变量
viper.BindEnv("port") // 绑定 MYAPP_PORT

View File

@@ -61,14 +61,19 @@ mkdir go-auth-api && cd go-auth-api
go mod init go-auth-api
# 安装依赖
go get -u github.com/gin-gonic/gin
go get -u gorm.io/gorm
go get -u gorm.io/driver/sqlite
go get -u github.com/spf13/viper
go get -u go.uber.org/zap
go get -u github.com/golang-jwt/jwt/v4
go get -u golang.org/x/crypto
go get -u gopkg.in/natefinch/lumberjack.v2
go get github.com/gin-gonic/gin@v1.10.0
go get github.com/gin-contrib/sse@v0.1.0
go get github.com/go-playground/validator/v10@v10.20.0
go get gorm.io/gorm@v1.25.7
go get gorm.io/driver/sqlite@v1.5.6
go get github.com/spf13/viper@v1.18.2
go get github.com/spf13/afero@v1.11.0
go get go.uber.org/zap@v1.27.0
go get golang.org/x/crypto@v0.21.0
```
> **版本说明**:代码兼容 Go 1.18+ 版本(建议 1.22+ 体验最佳性能)
@@ -491,10 +496,10 @@ func Login(cfg *Config) gin.HandlerFunc {
// 获取用户信息
func GetProfile(c *gin.Context) {
userID := c.GetUint("user_id")
userID, _ := c.Get("user_id")
var user User
if err := DB.First(&user, userID).Error; err != nil {
if err := DB.First(&user, userID.(uint)).Error; err != nil {
c.JSON(404, gin.H{"error": "User not found"})
return
}
@@ -504,7 +509,7 @@ func GetProfile(c *gin.Context) {
// 更新用户信息
func UpdateProfile(c *gin.Context) {
userID := c.GetUint("user_id")
userID, _ := c.Get("user_id")
var req struct {
Name string `json:"name"`
@@ -517,13 +522,13 @@ func UpdateProfile(c *gin.Context) {
return
}
if err := DB.Model(&User{}).Where("id = ?", userID).Updates(req).Error; err != nil {
if err := DB.Model(&User{}).Where("id = ?", userID.(uint)).Updates(req).Error; err != nil {
Logger.Error("Failed to update user", zap.Error(err))
c.JSON(500, gin.H{"error": "Failed to update profile"})
return
}
Logger.Info("User profile updated", zap.Uint("user_id", userID))
Logger.Info("User profile updated", zap.Uint("user_id", userID.(uint)))
c.JSON(200, gin.H{"message": "Profile updated successfully"})
}
@@ -563,8 +568,8 @@ type Config struct {
} `mapstructure:"database"`
JWT struct {
Secret int `mapstructure:"secret"`
Expire int `mapstructure:"expire"`
Secret string `mapstructure:"secret"`
Expire int `mapstructure:"expire"`
} `mapstructure:"jwt"`
Logging struct {
@@ -714,7 +719,7 @@ func main() {
protected.Use(AuthMiddleware(cfg))
{
protected.GET("/profile", GetProfile)
protected.PUT("/profile", UpdateProfile(cfg))
protected.PUT("/profile", UpdateProfile)
}
// 启动服务器