【发布时间】:2017-05-13 12:49:39
【问题描述】:
我已经使用golang、gin 和gorp 实现了rest api
Employee structure:
type Employee struct {
Id int64 `db:"id" json:"id"`
Firstname string `db:"firstname" json:"firstname"`
Lastname string `db:"lastname" json:"lastname"`
Dob time.Time `db:"dob" json:"dob"`
Skills []string `db:skills json:"skills"`
}
在POST发送请求为:
func PostEmployee(c *gin.Context) {
var emp Employee
c.Bind(&emp)
skills, _ := json.Marshal(emp.Skills)
if emp.Firstname != "" && emp.Lastname != "" {
if insert, _ := dbmap.Exec(`INSERT INTO employee (firstname, lastname, dob, skills) VALUES (?, ?, ?, ?)`, emp.Firstname, emp.Lastname, emp.Dob, skills); insert != nil {
emp_id, err := insert.LastInsertId()
.....
}
......
}
这会将数据保存到mysql 数据库,效果很好。
为了从数据库中检索数据,实现GET请求
func GetEmployees(c *gin.Context) {
var emps []Employee
_, err := dbmap.Select(&emps, "SELECT * FROM employee")
log.Println(err)
if err == nil {
c.JSON(200, emps)
} else {
c.JSON(404, gin.H{"error": "no employee(s) into the table"})
}
GET 查询不提供数据库中的任何数据,log.Println(err) 日志显示:
Scan error on column index 4: unsupported Scan, storing driver.Value type []uint8 into type *[]string
有什么想法吗?
【问题讨论】:
-
看起来选定的“技能”列未转换为 [] 字符串。数据库中employee.skills 的数据类型是什么?可能需要更改为 []byte 或 string 作为 Employee 结构中的技能类型。
-
在数据库中
Skills是varchar(255)类型。 @马克 -
将 Employee.Skills 从 []string 更改为 string
-
Skills是可重复字段,因此选择 []string(slice)。POST的示例 JSON 是curl -i -X POST -H "Content-Type: application/json" -d "{ \"firstname\": \"Thea\", \"lastname\": \"Queen\", \"dob\": \"2014-10-19T23:08:24Z\", \"skills\": [\"Go\", \"C\",\"Ruby\"] }" http://localhost:9090/api/v1/emps -
代码将技能作为单个字符串插入(通过将技能编组为 json),因此我认为您必须将其选择为单个字符串。我怀疑 gorp 会将 varchar(255) 转换为一段字符串。