Search code examples
gogo-ginhtmx

htmx form + gin unable to properly read request body


I have this form using htmx, trying 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>

The 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 include the input value as a parameter but I'm fairly certain there's a way to do that in the request body and I'm just missing something. How do I get the request body or query the "todo" input?


Solution

  • I think you are just getting a 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://pkg.go.dev/net/http#Request.FormValue