Go lang create map from database results without using predefined struct
Published on 07.12.2015
I created some function which get "random" data from MySQL database and return it as JSON. Here is some example code for achieve this, I skipped boring part with imports and creating net/http server and error handling is skipped.
db, _ := sql.Open( "mysql", "user=demo dbname=demo password=test") rows, _ := db.Query("select * from sites") columns, _ := rows.Columns() count := len(columns) values := make([]interface{}, count) valuePtrs := make([]interface{}, count) final_result := map[int]map[string]string{} result_id := 0 for rows.Next() { for i, _ := range columns { valuePtrs[i] = &values[i] } rows.Scan(valuePtrs...) tmp_struct := map[string]string{} for i, col := range columns { var v interface{} val := values[i] b, ok := val.([]byte) if (ok) { v = string(b) } else { v = val } tmp_struct[col] = fmt.Sprintf("%s",v) } final_result[ result_id ] = tmp_struct result_id++ } fmt.Println(final_result)