-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
49 lines (39 loc) · 920 Bytes
/
db.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
package database
import (
"context"
"errors"
"github.com/asdine/storm"
"net/http"
)
var (
errContextIsNull = errors.New("The context is null")
errNotFountInContext = errors.New("The db is not found in context")
)
type key int
const (
dbKey key = iota
)
func NewContext(ctx context.Context, db *storm.DB) context.Context {
return context.WithValue(ctx, dbKey, db)
}
func NewHandler(db *storm.DB) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r != nil {
r = r.WithContext(NewContext(r.Context(), db))
}
next.ServeHTTP(w, r)
})
}
}
// FromContext retruns db
func FromContext(ctx context.Context) (*storm.DB, error) {
if ctx == nil {
return nil, errContextIsNull
}
db, ok := ctx.Value(dbKey).(*storm.DB)
if !ok {
return nil, errNotFountInContext
}
return db, nil
}