I want the lowercase to be a string when I read it from the database. I know this can be done in SQL, but this is my first day with go, and this is more a proof of concept (and understanding of go), rather than an actual requirement.
type EmailAddress should always be lowercase if read from db using the Scan interface, it breaks with panic: interface conversion: interface [] uint8, not a string
package main
import (
"database/sql"
"github.com/kisielk/sqlstruct"
_ "github.com/lib/pq"
"log"
"strings"
)
type EmailAddress string
func (g *EmailAddress) Scan(src interface{}) error {
*g = EmailAddress(strings.ToLower(src.(string)))
return nil
}
type User struct {
Id int
MobilePhone string `sql:"mobile_phone"`
Email EmailAddress
}
func main() {
db, _ := sql.Open("postgres", "host=localhost dbname=test sslmode=disable")
defer db.Close()
rows, _ := db.Query("SELECT id, mobile_phone, COALESCE(email,'') as email FROM users limit 5")
for rows.Next() {
var t User
_ = sqlstruct.Scan(&t, rows)
log.Printf("%+v\n", t)
}
}
source
share