Martin Ocando
Martin Ocando

Reputation: 1828

Golang Structs/Interfaces

I'm trying to do something to bring the SQL results dynamically structure, basically I want to run a function by passing the rows and the structure(to get the data type and make one) and return in interface array.

Anyone know how I can do?

I dont want pass the direct "User" struct as param.. that is not dynamically

type User struct{
   Id_user int `json:"id_user"`
   Name string `json:"name"`
   Email string `json:"email"`
   Username string `json: "username"`
}

func main() {
  var user User
  rows, _ := db.Query("SELECT id_user, name, email, username FROM users")
  json.NewEncoder(w).Encode(StructRow(user, rows)) 
}

func StructRow(u interface{}, rows *sql.Rows)[]interface{}{
   var data []interface{}
   for rows.Next() {

      //How i can create a "user" here, dynamically
      //for Example
      //var user reflect.TypeOf(u)

      _ = rows.Scan(StrutForScan(&user)...)
      data = append(data, user)
   }
   return data
}

func StrutForScan(u interface{}) []interface{} {
   val := reflect.ValueOf(u).Elem()
   v := make([]interface{}, val.NumField())
   for i := 0; i < val.NumField(); i++ {
      valueField := val.Field(i)
      v[i] = valueField.Addr().Interface()
   }
   return v
}

Upvotes: 0

Views: 1641

Answers (1)

hitesh_noty
hitesh_noty

Reputation: 385

Changing your function StructRow to

 func StructRow(u interface{}, rows *sql.Rows) []interface{} {
    var data []interface{}
    for rows.Next() {

         t := reflect.TypeOf(u)
         val := reflect.New(t).Interface()

         errScan := rows.Scan(StrutForScan(val)...)
         if errScan != nil {
             //proper err handling
         }
         data = append(data, val)
    }
    return data
 }

will fix it. I guess. For more on reflect package go to: https://golang.org/pkg/reflect/

Upvotes: 1

Related Questions