首页 > 文章列表 > 无法在gin中正确解析 htmx 表单的请求正文

无法在gin中正确解析 htmx 表单的请求正文

498 2024-05-17
问题内容

我使用 htmx 有这个表单,尝试将第一个输入的输入值发送到 gin 服务器

<form hx-post="/addtodo" hx-ext="json-enc" hx-trigger="submit" hx-target="#todos" hx-swap="outerhtml">
    <input type="text" placeholder="todo" name="todo" />
    <input type="submit" />
</form>

<ol id="todos"></ol>

gin 服务器

r.POST("/addToDo", func(c *gin.Context) {
    fmt.Println(c.Request.Body)
    // ^this prints "&{0xc0000b2000 <nil> <nil> false true {0 0} false false false 0xeaee20}"

    jsonData, err := ioutil.ReadAll(c.Request.Body)

    if err != nil {
        fmt.Println("something went wrong here boys")
        return
    }

    fmt.Println(jsonData)
    // ^this prints "[116 111 100 111 61 104 101 108 108 111]"
})

我考虑过让 post 请求 url 包含输入值作为参数,但我相当确定在请求正文中有一种方法可以做到这一点,但我只是错过了一些东西。如何获取请求正文或查询“todo”输入?


正确答案


我认为您只是将字符串作为 []byte 获取。

a := []byte{116, 111, 100, 111, 61, 104, 101, 108, 108, 111}
  fmt.Print(string(a))

todo=hello

我认为您不需要自己解析这个 todo=hello 。您可以只使用:

https://pkg.go.dev/net/http#request.formvalue