Gin: Binding array of objects from post form

Created on 10 Dec 2019  路  3Comments  路  Source: gin-gonic/gin

Description

Are there a possibility to bind post form values from array of objects using gin?

How to reproduce

I have post form like

<input type="text" name="class">
<!-- first student -->
<input type="text" name="students[][first]">
<input type="text" name="students[][last]">
<input type="text" name="students[][age]">

<!-- second student -->
<input type="text" name="students[][first]">
<input type="text" name="students[][last]">
<input type="text" name="students[][age]">

And go code

type Student struct {
    First string `form:"first"`
    Last  string `form:"last"`
    Age   int    `form:"age"`
}
type Class struct {
    Class    string    `form:"class"`
    Students []Student `form:"students[]"`
}
func Handle(c *gin.Context) {
    err := c.Request.ParseForm()
    if err != nil {
        log.Fatal(err)
    }
    class:= new(Class)

    err = c.Bind(class)
    if err != nil {
        log.Fatal(err)
    }
    log.Println(c.Request.PostForm)
    log.Println(class)
}

I receive next output

map[students[][first]:[John Jack] students[][last]:[Johny Jacky] students[][age]:[20 30] class:[myclass]]
&{myclass []}

But I expect to receive array of structs Student and get output like

&{myclass [{John Johny 20} {Jack Jacky 30}]} 

How is it possible to do it?

Environment

  • go version: go version go1.12.7 linux/amd64
  • gin version (or commit ref): v1.4.0
  • operating system: Ubuntu 16.10

Similar issue
https://github.com/gin-gonic/gin/issues/1523

All 3 comments

Unfortunately it is not possible yet.

same question,hope support

Can't wait to see this supported! Coming from PHP, things like this were very common.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mastrolinux picture mastrolinux  路  3Comments

cxk280 picture cxk280  路  3Comments

kekemuyu picture kekemuyu  路  3Comments

ccaza picture ccaza  路  3Comments

sofish picture sofish  路  3Comments