doulu1020 2018-11-16 07:07
浏览 56

GOLANG>如何将Ajax json数据绑定到自定义结构类型?

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?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 delta降尺度计算的一些细节,有偿
    • ¥15 Arduino红外遥控代码有问题
    • ¥15 数值计算离散正交多项式
    • ¥30 数值计算均差系数编程
    • ¥15 redis-full-check比较 两个集群的数据出错
    • ¥15 Matlab编程问题
    • ¥15 训练的多模态特征融合模型准确度很低怎么办
    • ¥15 kylin启动报错log4j类冲突
    • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
    • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序