Created
April 23, 2015 01:32
-
-
Save dugancathal/a13fc1603aaf7cbabe6a to your computer and use it in GitHub Desktop.
A quick example of tagging using Postgres in Golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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