0

我从反应前端收到以下 POST 请求 json 数据

{
    "field_one": "first",
    "field_two": "second",
    "field_three": "3.00"
}

但我希望 golang 在处理请求之前将其转换为此

{
    "field_one": "first",
    "field_two": "second",
    "field_three": 3.00
}

我想将field_threefrom 字符串转换为float64,但我无法让 golang 接受字符串并处理正确的数据类型

这是我处理 POST 请求数据的 golang 函数

func PostCreate(c *fiber.Ctx) error {
    
    type PostCreateData struct {
        fieldOne       string  `json:"field_one" form:"field_one" validate:"required"`
        fieldTwo       string  `json:"field_two" form:"field_two" validate:"required"`
        fieldThree     float64 `json:"field_three" form:"field_three" validate:"required"`
    }

    data := PostCreateCreateData{}

    if err := c.BodyParser(&data); err != nil {
        return err
    }

    validate := validator.New()
        if err := validate.Struct(data); err != nil {
        return err
    }

    postCreate := models.PostCreate{
        fieldOne:         data.fieldOne,
        fieldTwo:         data.fieldTwo,
        fieldThree:       float64(data.fieldThree),
    }

    database.DB.Create(&postCreate)
    return c.JSON(postCreate)
}

目前该请求没有得到处理,因为错误的数据类型field_three应该是float64但前端将所有内容作为字符串发送

我在这里缺少哪些步骤?

4

1 回答 1

0

通过将函数更新为此修复

func PostCreate(c *fiber.Ctx) error {
    
    type PostCreateData struct {
        fieldOne       string  `json:"field_one" form:"field_one" validate:"required"`
        fieldTwo       string  `json:"field_two" form:"field_two" validate:"required"`
        fieldThree     float64 `json:"field_three,string" form:"field_three" validate:"required"`
    }

    data := PostCreateCreateData{}

    if err := c.BodyParser(&data); err != nil {
        return err
    }

    validate := validator.New()
        if err := validate.Struct(data); err != nil {
        return err
    }

    postCreate := models.PostCreate{
        fieldOne:         data.fieldOne,
        fieldTwo:         data.fieldTwo,
        fieldThree:       float64(data.fieldThree),
    }

    database.DB.Create(&postCreate)
    return c.JSON(postCreate)
}

所以更新了结构以期望正文中的字符串

fieldThree     float64 `json:"field_three,string" form:"field_three" validate:"required"`

像魅力一样工作!!!

于 2022-01-17T08:52:30.087 回答