sample pg <-> go code for dealing with pg points.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 

55 lines
975 B

package point
import (
"bytes"
"database/sql/driver"
"errors"
"fmt"
"strconv"
_ "github.com/lib/pq"
)
type Point struct {
Lat, Lng float64
}
func (p Point) Value() (driver.Value, error) {
tuple := fmt.Sprintf("(%f, %f)", p.Lat, p.Lng)
return driver.Value([]byte(tuple)), nil
}
func (p *Point) Scan(src interface{}) error {
var source []byte
var err error
switch src.(type) {
case string:
source = []byte(src.(string))
case []byte:
source = src.([]byte)
default:
return errors.New("Incompatible type for Point")
}
lp := bytes.IndexRune(source, '(')
c := bytes.IndexRune(source, ',')
rp := bytes.IndexRune(source, ')')
if lp == -1 || c == -1 || rp == -1 {
return fmt.Errorf(
"incorrect format from pg for Point: %s",
source,
)
}
p.Lat, err = strconv.ParseFloat(string(source[lp+1:c]), 64)
if err != nil {
return err
}
p.Lng, err = strconv.ParseFloat(string(source[c+1:rp]), 64)
if err != nil {
return err
}
return nil
}