用于postgres数据库的golang中的枚举类型值的Json绑定

时间:2016-08-19 05:31:16

标签: postgresql go

我正在实现一个rest api,我发送了一个json请求体。

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在我的数据库中的类型为enum。如何在我的Service结构中对其进行绑定?我可以绑定Name字段,因为它是数据库中的VARCHAR类型。但是当我在结构中添加Servicetype时,它无法绑定。我使用postgres作为我的数据库。

1 个答案:

答案 0 :(得分:1)

Servicetype 必须实现ScannerValuer接口。

了解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
}
相关问题