Mercurial > gemma
view auth/connection.go @ 340:4c211ad5349e
Embed Reader and Writer in BinReader and BinWriter to make API more distinct.
author | Sascha L. Teichmann <teichmann@intevation.de> |
---|---|
date | Sun, 05 Aug 2018 15:48:36 +0200 |
parents | 33b59c848771 |
children |
line wrap: on
line source
package auth import ( "database/sql" "errors" "io" "log" "sync" "time" "gemma.intevation.de/gemma/misc" ) var ErrNoSuchToken = errors.New("No such token") const ( maxOpen = 16 maxDBIdle = time.Minute * 5 ) type Connection struct { session *Session access time.Time db *sql.DB refCount int mu sync.Mutex } func (c *Connection) serialize(w io.Writer) error { if err := c.session.serialize(w); err != nil { return err } access, err := c.last().MarshalText() if err != nil { return err } wr := misc.BinWriter{w, nil} wr.WriteBin(uint32(len(access))) wr.WriteBin(access) return wr.Err } func (c *Connection) deserialize(r io.Reader) error { session := new(Session) if err := session.deserialize(r); err != nil { return err } rd := misc.BinReader{r, nil} var l uint32 rd.ReadBin(&l) access := make([]byte, l) rd.ReadBin(access) if rd.Err != nil { return rd.Err } var t time.Time if err := t.UnmarshalText(access); err != nil { return err } *c = Connection{ session: session, access: t, } return nil } func (c *Connection) set(session *Session) { c.session = session c.touch() } func (c *Connection) touch() { c.mu.Lock() c.access = time.Now() c.mu.Unlock() } func (c *Connection) last() time.Time { c.mu.Lock() access := c.access c.mu.Unlock() return access } func (c *Connection) close() { if c.db != nil { if err := c.db.Close(); err != nil { log.Printf("warn: %v\n", err) } c.db = nil } }