gpt4 book ai didi

go - 获取对象返回空字符串作为值Golang

转载 作者:行者123 更新时间:2023-12-01 20:27:06 25 4
gpt4 key购买 nike

我正在尝试使用gorm从数据库中获取用户,但得到200响应,但用户对象的值为空

{
"id": "",
"firstName": "",
"lastName": "",
"email": "",
"createdAt": "0001-01-01T00:00:00Z",
"updatedAt": "0001-01-01T00:00:00Z",
"deletedAt": null
}
这是我的模型和我的reg方法
func (user *User) Get(db *gorm.DB, uid string) *errors.Error {
fmt.Println("This is user ID %s", uid)

var err error
err = db.Debug().Model(User{}).Where("id = ?", uid).Take(&user).Error
if err != nil {
return errors.NewBadRequestError(fmt.Sprintf("error when trying to get user: %s", err.Error()))
}
if gorm.IsRecordNotFoundError(err) {
return errors.NewBadRequestError(fmt.Sprintf("user not found: %s", err.Error()))
}
return nil
}
该模型是
type User struct {
ID string `gorm:"primary_key;" json:"id"`
FirstName string `gorm:"size:255;not null;column:firstName" json:"firstName"`
LastName string `gorm:"size:255;not null;column:lastName" json:"lastName"`
Email string `gorm:"size:100;not null;unique;column:email" json:"email"`
CreatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP;column:createdAt" json:"createdAt"`
UpdatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP;column:updatedAt" json:"updatedAt"`
DeletedAt *time.Time `sql:"index;column:deletedAt" json:"deletedAt"`
}
我的服务逻辑
func GetUser(userId string) (*users.User, *errors.Error) {
// result := &users.User{Base: {

// }, }
fmt.Println("This is user ID 2 %s", userId)
result := &users.User{}
if err := result.Get(database.DB, userId); err != nil {
return nil, err
}
return &users.User{}, nil
}
我的 Controller
func GetUser(c *gin.Context) {
userId := c.Param("user_id")
fmt.Println(userId)

user, getErr := services.GetUser(userId)
if getErr != nil {
// TODO: handle user createing error
c.JSON(getErr.Status, getErr)
return
}
c.JSON(http.StatusOK, user)
}

最佳答案

在服务逻辑中,您将返回一个指针而不是一个值。

func GetUser(userId string) (*users.User, *errors.Error) {

fmt.Println("This is user ID 2 %s", userId)
result := &users.User{}
if err := result.Get(database.DB, userId); err != nil {
return nil, err
}
return &users.User{}, nil
}

它应该是:
func GetUser(userId string) (*users.User, *errors.Error) {
fmt.Println("This is user ID 2 %s", userId)
result := &users.User{ID: userId}
if err := result.Get(database.DB, userId); err != nil {
return nil, err
}
return result, nil
}

关于go - 获取对象返回空字符串作为值Golang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60074426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com