go - htmx 表单 + gin 无法正确读取请求正文

标签 go go-gin htmx

我使用 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=你好

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

https://pkg.go.dev/net/http#Request.FormValue

关于go - htmx 表单 + gin 无法正确读取请求正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76644869/

相关文章:

go - 将 null 分配给 JSON 字段而不是空字符串

go - Golang会将文字翻译到下一行

go - 在 Golang 中使用 Gin gonic 和一些调度器

sqlite - Golang/ Gin : How to Pass db to router functions

file - 如何在 Go 中将十六进制字节写入文本文件?

go - 如何将额外的参数传递给 Echo mux 处理程序?

go - 高并发下Go `net/http`的一些困惑

django - 如何使用 (HTMX) 更新两个 HTML 模板元素?

javascript - Tom-Select 作为 Django 小部件

google-apps-script - 缺少 Apps 脚本网络 Hook 和 Access-Control-Allow-Origin header