How to use the scan interface to enter a string read from a database

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)
  }
}
+4
source share
1 answer

[]uint8, EmailAddress , . , - uint8. , , : http://play.golang.org/p/iN5y3PaFAL

, :

func (g *EmailAddress) Scan(src interface{}) error {
  b, ok := src.([]byte)
  if !ok {
    return fmt.Errorf("expected []byte, got %T", src)
  }
  *g = EmailAddress(strings.ToLower(string(b))
  return nil
}
+9

All Articles