GOLANG > How to bind ajax json data to custom stru

2019-06-10 08:12发布

问题:

Why do not binding ajax json data for my custom struct type?

My env:

  • golang
  • echo framework

go binding function

/**
 *  function : Model Init
 */
func modelInit(c echo.Context) tetrisModel.Tetris {
    tetris := tetrisModel.DefaultInit()
    if err := c.Bind(tetris); err != nil {
        c.Logger().Error(err)
    }

    return *tetris
}

call modelInit

func Control(c echo.Context) tetrisModel.Tetris {
    tetris := modelInit(c)
    fmt.Println("=======================")
    fmt.Println(c.FormValue("nowBlockPositionX"))
    fmt.Println(tetris.NowBlockPositionX) // do not printing, why?
    fmt.Println("=======================")

    // ... ... other code... ... 
}

the result:

fmt.Println(c.FormValue("nowBlockPositionX")) > working

fmt.Println(tetris.NowBlockPositionX) not working / not printing, why? (do not binding)

I hope, this code will print the '3'

DefaultInit()

func DefaultInit() *Tetris {
    tetris := new(Tetris)

    // some default data setting...

    return tetris
}



tetris model code

type Tetris struct {
    NowBlockPositionX  int                `form:"nowBlockPositionX" json:"nowBlockPositionX"`
    NowBlockPositionY  int                `form:"nowBlockPositionY" json:"nowBlockPositionY"`
    NowBlock           map[string]int     `form:"nowBlock" json:"nowBlock"`

    // other data exists...
}



ajax json data(POST type)

{
    nowBlockPositionX: 3
    , nowBlockPositionY: 0
    , nowBlock: {L: 0}
    // other data exists...
}

I understand if go struct type has literal string (like this : form:"nowBlock" json:"nowBlock") then the structure auto bind('Bind function'). isn't it?