I have a simple form which I want to bind on the post request.
Here is the form:
<form method="post" action="/post">
<input type="text" name="name" placeholder="name"><br>
<input type="checkbox" name="agree"><br>
<button type="submit">submit</button>
</form>
I'm trying to bind it in such a stuct:
type PostForm struct {
Name string
Agree bool
}
Here is the whole code:
package main
import (
"github.com/labstack/echo/v4"
"html/template"
"io"
"log"
"net/http"
)
type Template struct {
templates *template.Template
}
func (t *Template) Render(w io.Writer, name string, data interface{}, _ echo.Context) error {
return t.templates.ExecuteTemplate(w, name, data)
}
type PostForm struct {
Name string
Agree bool
}
func main() {
e := echo.New()
e.Debug = true
e.Renderer = &Template{
templates: template.Must(template.ParseGlob("./templates/*.gohtml")),
}
e.GET("/", func(c echo.Context) error {
return c.Render(http.StatusOK, "index.gohtml", nil)
})
e.POST("/post", func(c echo.Context) error {
var form PostForm
err := c.Bind(&form)
if err != nil {
return c.String(http.StatusInternalServerError, err.Error())
}
return c.JSON(http.StatusOK, form)
})
log.Fatalln(e.Start(":3000"))
}
When I do post request with unchecked Agree field, it works fine:
{
"Name": "sdfgsdfg",
"Agree": false
}
But when I send the post with checked checkbox, there is an error:
code=400, message=strconv.ParseBool: parsing "on": invalid syntax, internal=strconv.ParseBool: parsing "on": invalid syntax
What I'm doing wrong?
Here is the repo on github with all code: https://github.com/max-block/q__echo_bind_checkbox
Aucun commentaire:
Enregistrer un commentaire