4

Is there an easy way to list / iterate through all post values using Gin Gonic? (Go)

I have tried:

c.Request.ParseForm()
for key, value := range c.Request.PostForm {
    log.Printf("POST %v = %v",key,value)
}

But this shows no values, however when I test the values directly from context:

log.Printf("POST email = %v", c.PostForm("email")

It outputs fine.

What I'm trying to do is to map all post values into a gin.H{} context, so that upon failure I can pass the posted values back into the .HTML template context and have them prefilled (along with my error message). Best I've found is manually wiring each POST value to the gin.H{} map, but for a large form these seems verbose and not ideal.

Zoyd
  • 3,449
  • 1
  • 18
  • 27
BadPirate
  • 25,802
  • 10
  • 92
  • 123
  • looking into the implementation of `c.PostForm()` i assume that the `PostForm` has not been parsed and thus might not contain any value https://github.com/gin-gonic/gin/blob/develop/context.go#L264-L276 – phoet Oct 11 '16 at 19:48
  • @phoet - Kind of looks like that... but shouldn't `ParseForm()` call parse? What's the fix? Do I need to call `ParseMultipartForm` instead? – BadPirate Oct 11 '16 at 21:00

2 Answers2

5

We also needed something like @BadPirate describes so if anyone need for gin 1.6.2

func register(c *gin.Context){
    c.MultipartForm()
    for key, value := range c.Request.PostForm {
        log.Printf("%v = %v \n",key,value)
    }
}

Thanks @BadPirate and @phoet for the info.

Fernando Leal
  • 76
  • 1
  • 2
0

Issue here was the form (not shown) was a multipart form. ParseForm does not parse multipart forms, and thus, no data. The fix is to call ParseMultipartForm instead. Thanks to @phoet for pointing at the method in Gin Gonic for PostForm (which calls ParseMultipartForm for you, and does so automatically), which helped lead me to the answer.

BadPirate
  • 25,802
  • 10
  • 92
  • 123