I want to retrieve records from a database and marshall those to json. I have about 30 different tables, so I want generic functions that will work with all and any of those tables. I use xorm for database access.
I have managed to create DRY functions that retrieve the data, mostly thanks to this question & answer
This works, can marshal all records to json:
type user struct {
Id int64 `json:"id"`
Name string `json:"name"`
}
// type post
// etc.
type tableRecord struct {
PrimaryKey string
Data interface{}
}
var ListOfTables = map[string]tableRecord{
"users":{"id", &[]user{}}, // type user is struct for xorm with json annotation
//"posts":{"post_id", &[]post{}},
// etc..
}
for tableName, rec := range ListOfTables {
err := xorm.Find(rec.Data)
if err != nil {
log.Print(err)
}
out, err := json.Marshal(rec.Data)
if err != nil {
log.Print(err)
}
log.Print(string(out)) // this yields json array
}
However I struggle with ability to marshal a single record to json. I have gone around looking for ways to iterate over an interface{}, that holds a slice, found this and similar topics. Tried:
switch reflect.TypeOf(reflect.ValueOf(rec.Data).Elem().Interface()).Kind() {
case reflect.Slice:
s := reflect.ValueOf(reflect.ValueOf(rec.Data).Elem().Interface())
for i := 0; i < s.Len(); i++ {
entry := s.Index(i)
log.Printf("%v\n", entry) // prints {1 John Doe}
// log.Print(reflect.ValueOf(entry))
data, err := json.MarshalIndent(entry, " ", " ")
if err != nil {
log.Print(err)
}
log.Println(string(data)) // prints {} empty
}
}
Of course, if I specify that rec.Data
is *[]user
it works, but then I would have to rewrite such code for each table, which is not what I am after.
switch t := rec.Data.(type) {
case *[]user:
for _, entry := range *t {
// log.Printf("loop %v", entry)
data, err := json.MarshalIndent(entry, " ", " ")
if err != nil {
log.Print(err)
}
log.Println(string(data)) // yields needed json for single record
}
}
Or maybe there is a completely different, better approach how to solve such - any record of database to json.
UPDATE The problem now is, that Xorm expects the struct? I will have to read xorm possibilities and limitations.
slice := record.Slice()
log.Print(reflect.TypeOf(slice))
err = env.hxo.In(record.PrimaryKey(), insertIds).Find(slice) // or &slice
if err != nil {
log.Print(err) // Table not found
}
// this works
var slice2 []*user
err = env.hxo.In(record.PrimaryKey(), insertIds).Find(&slice2)
if err != nil {
log.Print(err) //
}