-
Notifications
You must be signed in to change notification settings - Fork 1
/
http_context.go
46 lines (38 loc) · 1.29 KB
/
http_context.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
package gcloudcx
import (
"context"
"net/http"
"github.com/gildas/go-errors"
)
type key int
// ClientContextKey is the key to store Client in context.Context
const ClientContextKey key = iota + 54329
// ToContext stores this Client in the given context
func (client *Client) ToContext(parent context.Context) context.Context {
return context.WithValue(parent, ClientContextKey, client)
}
// ClientFromContext retrieves a Client from a context
func ClientFromContext(context context.Context) (*Client, error) {
value := context.Value(ClientContextKey)
if value == nil {
return nil, errors.ArgumentMissing.With("Client")
}
if client, ok := value.(*Client); ok {
return client, nil
}
return nil, errors.ArgumentInvalid.With("Client", value)
}
// HttpHandler wraps the client into an http Handler
func (client *Client) HttpHandler() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log := client.Logger.Scope("middleware")
if client.Grant.AccessToken().LoadFromCookie(r, "pcsession").IsValid() {
log.Infof("Gcloud Token loaded from cookies")
} else {
log.Debugf("Gcloud Token not found in cookies")
}
next.ServeHTTP(w, r.WithContext(client.ToContext(r.Context())))
})
}
}