-
Notifications
You must be signed in to change notification settings - Fork 29
/
cleanup.go
58 lines (49 loc) · 1.36 KB
/
cleanup.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package pgstore
import (
"log"
"time"
)
var defaultInterval = time.Minute * 5
// Cleanup runs a background goroutine every interval that deletes expired
// sessions from the database.
//
// The design is based on https://github.com/yosssi/boltstore
func (db *PGStore) Cleanup(interval time.Duration) (chan<- struct{}, <-chan struct{}) {
if interval <= 0 {
interval = defaultInterval
}
quit, done := make(chan struct{}), make(chan struct{})
go db.cleanup(interval, quit, done)
return quit, done
}
// StopCleanup stops the background cleanup from running.
func (db *PGStore) StopCleanup(quit chan<- struct{}, done <-chan struct{}) {
quit <- struct{}{}
<-done
}
// cleanup deletes expired sessions at set intervals.
func (db *PGStore) cleanup(interval time.Duration, quit <-chan struct{}, done chan<- struct{}) {
ticker := time.NewTicker(interval)
defer func() {
ticker.Stop()
}()
for {
select {
case <-quit:
// Handle the quit signal.
done <- struct{}{}
return
case <-ticker.C:
// Delete expired sessions on each tick.
err := db.deleteExpired()
if err != nil {
log.Printf("pgstore: unable to delete expired sessions: %v", err)
}
}
}
}
// deleteExpired deletes expired sessions from the database.
func (db *PGStore) deleteExpired() error {
_, err := db.DbPool.Exec("DELETE FROM http_sessions WHERE expires_on < now()")
return err
}