卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章33970本站已运行390

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

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

问题内容

我使用 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://www.php.cn/link/7476533956dd3568c1d787c5d33a547f

卓越飞翔博客
上一篇: 如何解决 Go 聊天应用程序中 cookie 未在本地主机端口之间传输的问题?
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏