douli8428 2016-08-19 05:31
浏览 65
已采纳

Json绑定用于Postgres数据库的Golang中的枚举类型值

I am implementing a rest api where I send a json request body.

type Service struct {
    id int64 `db:"id" json:"id"`
    Name string `form:"name" db:"name" json:"name" binding:"required"`
    Servicetype string `form:"type"  db:"type" json:"type" binding:"required"`
}

func myHandler(c *gin.Context) {
    if c.BindJSON(&json) == nil {
        fmt.Println(json.Servicetype)
    } else {
         fmt.Println("json binding error")
    }
}

Servicetype is of type enum in my database. How can I have binding for that in my Service struct? I am able to bind the Name field as it is of type VARCHAR in database. But it fails to bind when I add Servicetype in the struct. I am using postgres as my database.

  • 写回答

1条回答 默认 最新

  • dongou1970 2016-08-19 16:44
    关注

    Servicetype must implement Scanner and Valuer interfaces.

    Take a look on how std package does it for NullString

    // NullString represents a string that may be null.
    // NullString implements the Scanner interface so
    // it can be used as a scan destination:
    
    
    type NullString struct {
        String string
        Valid  bool // Valid is true if String is not NULL
    }
    
    // Scan implements the Scanner interface.
    func (ns *NullString) Scan(value interface{}) error {
        if value == nil {
            ns.String, ns.Valid = "", false
            return nil
        }
        ns.Valid = true
        return convertAssign(&ns.String, value)
    }
    
    // Value implements the driver Valuer interface.
    func (ns NullString) Value() (driver.Value, error) {
        if !ns.Valid {
            return nil, nil
        }
        return ns.String, nil
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

    报告相同问题?

    悬赏问题

    • ¥15 shopify网站提速
    • ¥15 深海控制器DSE7320MKII和博世ECU间can通讯知识
    • ¥15 Ru的复折射率用于FDTD 200nm到1200nm
    • ¥15 使用Fiddler抓包,textview的乱码如何解决
    • ¥50 trio连接驱动器报错
    • ¥15 有谁懂nhanes的权重计算啊
    • ¥15 欧姆龙PLC 电机控制 限位
    • ¥30 如何处理shell命令接收到的视频流并实时播放出来
    • ¥15 虚心请教C#的代码优化问题
    • ¥15 有偿求做台风过境全过程模拟仿真