package main import ( "database/sql" "log" _ "github.com/lib/pq" ) type Session struct { Id string UserId int64 } type User struct { Id int64 UserName string Password []byte } type Store interface { GetSession(id string) (*Session, bool) GetUser(name string) (*User, bool) } type PgStore struct { *sql.DB sessionCache map[string]*Session } func NewPgStore() *PgStore { db, err := sql.Open("postgres", "postgres://auth_master:pass@localhost/authdb") if err != nil { log.Panic(err) } return &PgStore{db, make(map[string]*Session)} } func (store *PgStore) GetSession(id string) (*Session, bool) { s, ok := store.sessionCache[id] if ok { return s, true } s = new(Session) row := store.QueryRow("SELECT id, user_id FROM session WHERE id = $1", id) if err := row.Scan(s.Id, s.UserId); err != nil { return nil, false } return s, true } func (store *PgStore) GetUser(name string) (*User, bool) { u := new(User) row := store.QueryRow("SELECT id, user_name, password FROM user WHERE user_name = $1", name) if err := row.Scan(u.Id, u.UserName, u.Password); err != nil { return nil, false } return u, true }