4

I've an HTML form:

<body>
<div>
  <form method="POST" action="/add"name="submitForm">
      <label>Message</label><input type="text" name="message" value="" />
      <input type="checkbox" name="complete" value=""> Complete<br>
      <input type="submit" value="submit" />
  </form>
</div>
</body>

Now I want to access both values (message and complete) at the same time when a POST occurs.

How can I do this in Go (gin gonic)?

I can do it in two times by using c.PostForm but is there a way to collect them both?:

func AddTodoHandler(c *gin.Context) {
    fmt.Println(c.PostForm("message"))
    fmt.Println(c.PostForm("complete"))

I tried fmt.Println(c.PostForm("submitForm")) but that did not work.

blackgreen
  • 34,072
  • 23
  • 111
  • 129
DenCowboy
  • 13,884
  • 38
  • 114
  • 210
  • I wonder, have you tried the method suggested on the documentation, i.e. using a struct to hold all values in the form (with optional validation via decorators), and then do a `ShouldBind` on them? Is there any reason why the two value *have* to be independent of each other, and not aggregated into a common struct? – Gwyneth Llewelyn Aug 05 '23 at 18:31

1 Answers1

1

I don't know if you've already solved this, but the way I managed to capture the 2 values simultaneously was by removing the value from the checkbox and using the Request.PostForm instead of the PostForm.

I tried using the form's name or id, but it seems that it's still not possible to get the data from them.

<body>
<div>
  <form method="POST" action="/add" name="submitForm"> << not work
      <label>Message</label><input type="text" name="message" value="" />
      <input type="checkbox" name="complete"> Complete<br> << remove value attribute
      <input type="submit" value="submit" />
  </form>
</div>
</body>
func AddTodoHandler(c *gin.Context) {
    fmt.Println(c.Request.PostForm)

Note: as my reputation is less than 50pts, I cannot comment on the post.

  • Why don't you use a struct to hold the two values, and then use `ShouldBind` on them, like the documentation says? The whole point of Gin is to give you an extra abstraction layer so that you don't need to _worry_ about those things... – Gwyneth Llewelyn Aug 05 '23 at 18:33