2016-08-19 35 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 
}