I need function that make query to databse.
I use github.com/gocraft/dbr, so i create helper function:
//SelectData - selects data from database
func SelectData(table, fields, where string, data interface{}) interface{} {
var ptr reflect.Value
ptr = reflect.New(reflect.TypeOf(data)) // create new pointer
obj := ptr.Interface()
sess := Session
query := sess.Select(fields).
From(table)
if len(where) > 0 {
query.Where(where)
}
_, err := query.Load(obj)
if err != nil {
panic(err)
}
return obj
}
then i try to use it:
//CheckUser - checks is user registered in db
func CheckUser(userid string) User {
var user User
var i interface{}
i = db.SelectData("users", "*", "", user)
fmt.Printf("=%#v \n", i)
user = i.(User)
return user
}
But i get runtime error:
interface conversion: interface {} is *models.User, not models.User
D:/Go/src/runtime/panic.go:513 (0x42ccb6)
gopanic: reflectcall(nil, unsafe.Pointer(d.fn), deferArgs(d), uint32(d.siz), uint32(d.siz))
D:/Go/src/runtime/iface.go:248 (0x4091ac)
panicdottypeE: panic(&TypeAssertionError{iface, have, want, ""})
C:/Users/vasalt/go/src/wcenter/models/model_user.go:29 (0x9dda3a)
CheckUser: user = i.(User)
C:/Users/vasalt/go/src/wcenter/controllers/ctrl_main.go:59 (0x9e03b6)
SetPageData: fmt.Printf("=result = %#v\n", models.CheckUser("1234"))
And debug output:
=&models.User{UID:sql.NullString{String:"1", Valid:true}, UserID:sql.NullString{String:"1234", Valid:true}, UserGroup:sql.NullString{String:"1", Valid:true}}
So it succesfully retrieve data from datbase, but it return &models.User
not just models.User
and i cant figure out how convert interface{}
with *models.User
to models.User
Aucun commentaire:
Enregistrer un commentaire