我有一個(gè)簡(jiǎn)單的表單,我想在發(fā)布請(qǐng)求上綁定它。這是表格:<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>我正在嘗試將其綁定在這樣的結(jié)構(gòu)中:type PostForm struct { Name string Agree bool}這是整個(gè)代碼:package mainimport ( "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"))}當(dāng)我使用未選中的同意字段發(fā)布請(qǐng)求時(shí),它工作正常:{ "Name": "sdfgsdfg", "Agree": false}但是當(dāng)我發(fā)送帶有選中復(fù)選框的帖子時(shí),出現(xiàn)錯(cuò)誤:code=400, message=strconv.ParseBool: parsing "on": invalid syntax, internal=strconv.ParseBool: parsing "on": invalid syntax我做錯(cuò)了什么?這是 github 上的所有代碼的倉庫:https ://github.com/max-block/q__echo_bind_checkbox
1 回答

鳳凰求蠱
TA貢獻(xiàn)1825條經(jīng)驗(yàn) 獲得超4個(gè)贊
<html>
<head></head>
<body>
<form method="post" action="/post">
<input type="text" name="name" placeholder="name"><br>
// set the value as "true"
<input type="checkbox" name="agree" value="true"><br>
<button type="submit">submit</button>
</form>
</body>
</html>
checkbox的默認(rèn)值為“on”,與go的“true”不同。
- 1 回答
- 0 關(guān)注
- 114 瀏覽
添加回答
舉報(bào)
0/150
提交
取消