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 如何修改pca中的feature函数
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R
  • ¥15 在线请求openmv与pixhawk 实现实时目标跟踪的具体通讯方法