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 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!