I've started my journey with the lang a couple of months ago, so I can't figure out some stuff yet.
I had a friend help me building an api, and now we are in the middle of the project when I noticed something was missing.
When I make a request to the api, the column name from the BD is not returned, so it doesn't build a correct json.
Can someone help me figure out how can I do it?
I have this code:
func QueryAndReturnStrings(query string) [][]string {
var final [][]string
rows, queryErr := connection.Query(query) // execute our query and get back the rows object from the sql library
if queryErr != nil {
log.Fatal(queryErr)
}
defer rows.Close() // defer rows.close() so we give our connection back when we’re done
queryColumns, colErr := rows.Columns()
if colErr != nil {
log.Fatal(colErr)
}
// Result is your slice string.
rawResult := make([][]byte, len(queryColumns)) // Then we make rawResult which is an array of array of bytes which is the length of the # of columns in our sql table (that’s pretty important)
var result []string
// dest = destination
dest := make([]interface{}, len(queryColumns)) // A temporary interface{} slice | then we create dest which is an array of interface{}
// we loop through dest and set it equal to a pointer to the corresponding index in rawResult so we have dest which is an array of pointers to arrays of bytes. (if you don’t really understand pointers, this is going to get really nuts.)
for i := range rawResult {
dest[i] = &rawResult[i] // Put pointers to each string in the interface slice
}
leng := len(queryColumns)
count := 0
for rows.Next() { // loops through each row in it’s raw sql form
err := rows.Scan(dest...)
if err != nil {
log.Fatal(err)
}
for _, raw := range rawResult {
count++
if raw == nil {
result = append(result, "\\N")
} else {
result = append(result, string(raw))
}
if count == leng {
count = 0
final = append(final, result)
result = nil
}
}
}
return final
}