-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathrouter.go
185 lines (143 loc) · 5.09 KB
/
router.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
package gbox
import (
"bytes"
"errors"
"io/ioutil"
"net/http"
"time"
"github.com/99designs/gqlgen/graphql/handler"
"github.com/99designs/gqlgen/graphql/playground"
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
"github.com/gbox-proxy/gbox/admin"
"github.com/gbox-proxy/gbox/admin/generated"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/jensneuse/graphql-go-tools/pkg/graphql"
"go.uber.org/zap"
)
const (
adminPlaygroundPath = "/admin"
adminGraphQLPath = "/admin/graphql"
playgroundPath = "/"
graphQLPath = "/graphql"
)
var ErrNotAllowIntrospectionQuery = errors.New("introspection query is not allowed")
func (h *Handler) initRouter() {
router := mux.NewRouter()
router.Path(graphQLPath).HeadersRegexp(
"content-type", "application/json*",
).Methods("POST").HandlerFunc(h.GraphQLHandle)
router.Path(graphQLPath).HeadersRegexp(
"upgrade", "^websocket$",
"sec-websocket-protocol", "^graphql-(transport-)?ws$",
).Methods("GET").HandlerFunc(h.GraphQLOverWebsocketHandle)
if h.Caching != nil {
router.Path(adminGraphQLPath).HeadersRegexp(
"content-type", "application/json*",
).Methods("POST").HandlerFunc(h.AdminGraphQLHandle)
}
if !h.DisabledPlaygrounds {
ph := playground.Handler("GraphQL playground", graphQLPath)
router.Path(playgroundPath).Methods("GET").Handler(ph)
if h.Caching != nil {
phAdmin := playground.Handler("Admin GraphQL playground", adminGraphQLPath)
router.Path(adminPlaygroundPath).Methods("GET").Handler(phAdmin)
}
}
if len(h.CORSOrigins) == 0 {
h.router = router
return
}
h.router = handlers.CORS(
handlers.AllowCredentials(),
handlers.AllowedOrigins(h.CORSOrigins),
handlers.AllowedHeaders(h.CORSAllowedHeaders),
)(router)
}
// GraphQLOverWebsocketHandle handling websocket connection between client & upstream.
func (h *Handler) GraphQLOverWebsocketHandle(w http.ResponseWriter, r *http.Request) {
reporter := r.Context().Value(errorReporterCtxKey).(*errorReporter)
if err := h.rewriteHandle(w, r); err != nil {
reporter.error = err
return
}
n := r.Context().Value(nextHandlerCtxKey).(caddyhttp.Handler)
wsr := newWebsocketResponseWriter(w, h)
reporter.error = h.ReverseProxy.ServeHTTP(wsr, r, n)
}
// GraphQLHandle ensure GraphQL request is safe before forwarding to upstream and caching query result of it.
func (h *Handler) GraphQLHandle(w http.ResponseWriter, r *http.Request) {
reporter := r.Context().Value(errorReporterCtxKey).(*errorReporter)
if err := h.rewriteHandle(w, r); err != nil {
reporter.error = err
return
}
gqlRequest, err := h.unmarshalHTTPRequest(r)
if err != nil {
h.logger.Debug("can not unmarshal graphql request from http request", zap.Error(err))
reporter.error = writeResponseErrors(err, w)
return
}
if err = h.validateGraphqlRequest(gqlRequest); err != nil {
reporter.error = writeResponseErrors(err, w)
return
}
h.addMetricsBeginRequest(gqlRequest)
defer func(startedAt time.Time) {
h.addMetricsEndRequest(gqlRequest, time.Since(startedAt))
}(time.Now())
n := r.Context().Value(nextHandlerCtxKey).(caddyhttp.Handler)
if h.Caching != nil {
cachingRequest := newCachingRequest(r, h.schemaDocument, h.schema, gqlRequest)
reverse := caddyhttp.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error {
return h.ReverseProxy.ServeHTTP(w, r, n)
})
if err = h.Caching.HandleRequest(w, cachingRequest, reverse); err != nil {
reporter.error = writeResponseErrors(err, w)
return
}
return
}
reporter.error = h.ReverseProxy.ServeHTTP(w, r, n)
}
func (h *Handler) unmarshalHTTPRequest(r *http.Request) (*graphql.Request, error) {
gqlRequest := new(graphql.Request)
rawBody, _ := ioutil.ReadAll(r.Body)
r.Body = ioutil.NopCloser(bytes.NewBuffer(rawBody))
copyHTTPRequest, err := http.NewRequest(r.Method, r.URL.String(), ioutil.NopCloser(bytes.NewBuffer(rawBody))) // nolint:noctx
if err != nil {
return nil, err
}
if err = graphql.UnmarshalHttpRequest(copyHTTPRequest, gqlRequest); err != nil {
return nil, err
}
if err = normalizeGraphqlRequest(h.schema, gqlRequest); err != nil {
return nil, err
}
return gqlRequest, nil
}
func (h *Handler) validateGraphqlRequest(r *graphql.Request) error {
isIntrospectQuery, _ := r.IsIntrospectionQuery()
if isIntrospectQuery && h.DisabledIntrospection {
return ErrNotAllowIntrospectionQuery
}
if h.Complexity != nil {
requestErrors := h.Complexity.validateRequest(h.schema, r)
if requestErrors.Count() > 0 {
return requestErrors
}
}
return nil
}
// AdminGraphQLHandle purging query result cached and describe cache key.
func (h *Handler) AdminGraphQLHandle(w http.ResponseWriter, r *http.Request) {
resolver := admin.NewResolver(h.schema, h.schemaDocument, h.logger, h.Caching)
gqlGen := handler.NewDefaultServer(generated.NewExecutableSchema(generated.Config{Resolvers: resolver}))
gqlGen.ServeHTTP(w, r)
}
func (h *Handler) rewriteHandle(w http.ResponseWriter, r *http.Request) error {
n := caddyhttp.HandlerFunc(func(http.ResponseWriter, *http.Request) error {
return nil // trick for skip passing cachingRequest to next handle
})
return h.Rewrite.ServeHTTP(w, r, n)
}