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 Arduino,利用modbus的RS485协议,进行对外置的温湿度传感器进行数据读取
  • ¥15 vhdl+MODELSIM
  • ¥20 simulink中怎么使用solve函数?
  • ¥30 dspbuilder中使用signalcompiler时报错Error during compilation: Fitter failed,求解决办法
  • ¥15 gwas 分析-数据质控之过滤稀有突变中出现的问题
  • ¥15 没有注册类 (异常来自 HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
  • ¥15 知识蒸馏实战博客问题
  • ¥15 用PLC设计纸袋糊底机送料系统
  • ¥15 simulink仿真中dtc控制永磁同步电机如何控制开关频率
  • ¥15 用C语言输入方程怎么