Home >Backend Development >Golang >html form + gin cannot read the request body correctly

html form + gin cannot read the request body correctly

WBOY
WBOYforward
2024-02-05 22:39:071130browse

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

Question content

I have this form using htmx and try to send the input value of the first input to the gin server

<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 server

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]"
})

I thought about having the post request url contain the input value as a parameter, but I'm pretty sure there's a way to do that in the request body, but I'm just missing something. How to get request body or query "todo" input?


Correct answer


I think you are just getting the string as a []byte.

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

todo=hello

I don't think you need to parse this todo=hello yourself. You can just use:

https://www.php.cn/link/7476533956dd3568c1d787c5d33a547f

The above is the detailed content of html form + gin cannot read the request body correctly. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete