2016-08-19 38 views
0

我正在实现一个休息API,我发送一个JSON请求正文。Json绑定枚举类型值在golang for postgres数据库

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

回答

1

服务类型必须实现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 
}