Gin Gonic array of values from PostForm

BadPirate picture BadPirate · Oct 11, 2016 · Viewed 11.7k times · Source

I'm trying to capture an array of Post values from HTML form using Go / Gin Gonic -- in PHP I would use something like:

<form method="POST" enctype="multipart/form-data" action="mygo">
 <input type=hidden name="emails[]" value="[email protected]">
 <input type=hidden name="emails[]" value="[email protected]">
 <input type=hidden name="emails[]" value="[email protected]">
</form>

However this doesn't seem to work with Gin Gonic (or Go for that matter).

I've also tried:

<form method="POST" enctype="multipart/form-data" action="mygo">
 <input type=hidden name="emails" value="[email protected]">
 <input type=hidden name="emails" value="[email protected]">
 <input type=hidden name="emails" value="[email protected]">
</form>

As elsewhere it is suggested that doing this would cause c.PostForm("emails") to return a slice. However in practice it seems that this instead returns the last value as a string instead :(

Interestingly, c.Request.PostForm returns an empty map, even if c.Request.ParseForm() is called first. What am I doing wrong?

Go Form:

func main() {
// ...
    router.POST("mygo",parseFunc)
}

func mygo(c *gin.Context) {
  c.Request.ParseForm()
  log.Printf("%v",c.Request.PostForm["emails"]) // ""
  log.Printf("%v",c.PostForm("emails") // "[email protected]"
}

Answer

Marcel Novy picture Marcel Novy · Oct 12, 2016

In order to make it works you have two ways here

<form method="POST" enctype="multipart/form-data" action="mygo">
 <input type=hidden name="emails" value="[email protected]">
 <input type=hidden name="emails" value="[email protected]">
 <input type=hidden name="emails" value="[email protected]">
</form>

r.POST("/", func(c *gin.Context) {
        c.Request.ParseMultipartForm(1000)
        for key, value := range c.Request.PostForm {
            fmt.Println(key,value)
        }
    })

either

    <form method="POST" action="mygo">
     <input type=hidden name="emails" value="[email protected]">
     <input type=hidden name="emails" value="[email protected]">
     <input type=hidden name="emails" value="[email protected]">
    </form>

 r.POST("/", func(c *gin.Context) {
            c.Request.ParseForm()
            for key, value := range c.Request.PostForm {
                fmt.Println(key,value)
            }
        })

Both gives the same result

emails [[email protected] [email protected] [email protected]]