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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵