Skip to content

Instantly share code, notes, and snippets.

@lengocgiang
Created August 15, 2017 10:08
Show Gist options
  • Save lengocgiang/82b075734b8e345ae4b844d32408ccd4 to your computer and use it in GitHub Desktop.
Save lengocgiang/82b075734b8e345ae4b844d32408ccd4 to your computer and use it in GitHub Desktop.
package main
import (
"errors"
"database/sql"
"encoding/json"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
type Shop struct {
AccessKey interface{} `json:"accessKey"`
Address string `json:"address"`
Country string `json:"country"`
CreatedAt string `json:"created_at"`
ID int `json:"id"`
RefID string `json:"ref_id"`
Zip string `json:"zip"`
}
func (m *MySQL) FindShopByDomain(domain string) (Shop, error) {
stmp, err := m.DB.Prepare("SELECT * FROM shops WHERE domain=?")
if err != nil {
fmt.Println("stmp:", err)
return types.Shop{}, err
}
defer stmp.Close()
rows, err := stmp.Query(domain)
if err != nil {
return types.Shop{}, err
}
// Get column names
columns, err := rows.Columns()
if err != nil {
return Shop{}, err
}
var shop Shop
result, _ := parseSQL(rows, columns)
if len(result) == 0 {
return types.Shop{}, errors.New("Not found")
}
// get first record
rawData, _ := json.Marshal(result[0])
err = json.Unmarshal(rawData, &shop)
if err != nil {
return types.Shop{}, err
}
return shop, nil
}
func parseSQL(rows *sql.Rows, columns []string) ([]map[string]interface{}, error) {
listResults := make([]map[string]interface{}, 0)
values := make([]interface{}, len(columns))
scanArgs := make([]interface{}, len(columns))
for i := 0; i < len(columns); i++ {
scanArgs[i] = &values[i]
}
for rows.Next() {
rows.Scan(scanArgs...)
entry := make(map[string]interface{})
for i, col := range values {
var v interface{}
val := values[i]
if b, ok := val.([]byte); ok {
v = string(b)
} else {
v = val
}
entry[col] = v
}
listResults = append(listResults, entry)
}
return listResults, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment