登录
首页 >  Golang >  Go问答

未在PATCH请求中检测到Golang布尔值

来源:stackoverflow

时间:2024-02-06 08:45:21 410浏览 收藏

亲爱的编程学习爱好者,如果你点开了这篇文章,说明你对《未在PATCH请求中检测到Golang布尔值》很感兴趣。本篇文章就来给大家详细解析一下,主要介绍一下,希望所有认真读完的童鞋们,都有实质性的提高。

问题内容

我正在尝试指示客户端是否处于活动状态的应用程序。 如果我手动将 clientactive 布尔值设置为 false,我可以成功将其转换为 true。但如果为 true,则不会设置为 false。 我正在使用 gofiber 和 gorm

模型/client.go

type client struct {
gorm.model
slug           string `json:"slug" gorm:"unique"`
clientname     string `json:"client_name"`
address        string `json:"address,omitempty"`
address2       string `json:"address_2,omitempty" gorm:"null"`
phone          string `json:"phone" gorm:"null"`
primaryemail   string `json:"primary_email" gorm:"null"`
secondaryemail string `json:"secondary_email" gorm:"null"`
clientactive bool `json:"client_active" gorm:"default:true"`
contacts     []contact
devices      []device
}

处理程序/clienthandler.go

func ClientUpdate(c \*fiber.Ctx) error {
slug := c.Params("slug")

    var data models.Client
    
    err := c.BodyParser(&data)
    if err != nil {
        return err
    }
    
    // todo: the ClientActive variable will set as true, but never false
    client := &models.Client{
        ClientName:     data.ClientName,
        Address:        data.Address,
        Address2:       data.Address2,
        Phone:          data.Phone,
        PrimaryEmail:   data.PrimaryEmail,
        SecondaryEmail: data.SecondaryEmail,
        ClientActive:   data.ClientActive,
    }
    
    err = database.DB.Model(&data).Where("slug = ?", slug).Updates(&client).Error
    if err != nil {
        return err
    }
    
    return c.JSON(client)

}

所有其他行更新都没有问题。唯一的问题是 clientactive 布尔值。

完整代码可在 https://github.com/simpleittools/assetapi 获取

我已确认数据是以布尔值形式发送的。我在数据库输入之前和之后都运行了 fmt.prtintln(client),它确实正确显示为 false。

我在此过程中没有收到任何错误。


正确答案


gorm 默认值文档说:

对于定义默认值的字段,任何零值(例如 0、''、false)都不会保存到数据库中,您可能需要使用指针类型或 scanner/valuer 来避免这种情况

通过将字段类型更改为 *bool 进行修复:

type Client struct {
    ⋮
    ClientActive *bool `json:"client_active" gorm:"default:true"`
    ⋮
}

本篇关于《未在PATCH请求中检测到Golang布尔值》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>