Skip to content

Instantly share code, notes, and snippets.

@dugancathal
Created April 23, 2015 01:32
Show Gist options
  • Save dugancathal/a13fc1603aaf7cbabe6a to your computer and use it in GitHub Desktop.
Save dugancathal/a13fc1603aaf7cbabe6a to your computer and use it in GitHub Desktop.
A quick example of tagging using Postgres in Golang
package main
import (
"bytes"
"database/sql"
"encoding/csv"
"errors"
"fmt"
_ "github.com/lib/pq"
)
type Post struct {
Id int64
Name string
Tags TagList
}
type TagList []string
func (self *TagList) Scan(src interface{}) error {
asBytes, ok := src.([]byte)
if !ok {
return error(errors.New("Scan source was not []bytes"))
}
buf := bytes.NewBuffer(asBytes[1 : len(asBytes)-1])
res, _ := csv.NewReader(buf).Read()
*self = TagList(res)
return nil
}
func main() {
db, _ := sql.Open("postgres", "postgres://localhost/ttaylor?sslmode=disable")
err := db.Ping()
if err != nil {
panic(err)
}
defer db.Close()
db.Exec("CREATE TABLE IF NOT EXISTS posts (id serial PRIMARY KEY, name varchar(255), tags varchar[]);")
db.Exec("TRUNCATE TABLE posts")
db.Exec("INSERT INTO posts (name, tags) VALUES ('My First Post', ARRAY['tone.silly', 'topic.intro']);")
row := db.QueryRow("SELECT * FROM posts LIMIT 1;")
var post Post
err = row.Scan(&post.Id, &post.Name, &post.Tags)
if err != nil {
panic(err)
}
for _, tag := range post.Tags {
fmt.Println("Tag:", tag)
}
fmt.Printf("%+v\n", post)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment