generated from datumforge/go-template
-
Notifications
You must be signed in to change notification settings - Fork 7
/
interceptor.go
55 lines (46 loc) · 1.61 KB
/
interceptor.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
package datumclient
import (
"context"
"fmt"
"net/http"
"strings"
"github.com/Yamashou/gqlgenc/clientv2"
"github.com/datumforge/datum/pkg/sessions"
)
// WithAuthorization adds the authorization header and session to the client request
func WithAuthorization(accessToken string, session string) clientv2.RequestInterceptor {
return func(
ctx context.Context,
req *http.Request,
gqlInfo *clientv2.GQLRequestInfo,
res interface{},
next clientv2.RequestInterceptorFunc,
) error {
// setting authorization header if its not already set
h := req.Header.Get("Authorization")
if h == "" {
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", accessToken))
}
// add session cookie
if strings.Contains(req.Host, "localhost") {
req.AddCookie(sessions.NewDevSessionCookie(session))
} else {
req.AddCookie(sessions.NewSessionCookie(session))
}
return next(ctx, req, gqlInfo, res)
}
}
// WithLoggingInterceptor adds a http debug logging interceptor
func WithLoggingInterceptor() clientv2.RequestInterceptor {
return func(ctx context.Context, req *http.Request, gqlInfo *clientv2.GQLRequestInfo, res interface{}, next clientv2.RequestInterceptorFunc) error {
fmt.Println("Request header sent:", req.Header)
fmt.Println("Request body sent:", req.Body)
return next(ctx, req, gqlInfo, res)
}
}
// WithEmptyInterceptor adds an empty interceptor
func WithEmptyInterceptor() clientv2.RequestInterceptor {
return func(ctx context.Context, req *http.Request, gqlInfo *clientv2.GQLRequestInfo, res interface{}, next clientv2.RequestInterceptorFunc) error {
return next(ctx, req, gqlInfo, res)
}
}