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

html form + gin cannot read the request body correctly

WBOY
Release: 2024-02-05 22:39:07
forward
1113 people have browsed it

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>
Copy after login

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

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))
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template