-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraphql.go
More file actions
63 lines (51 loc) · 1.75 KB
/
graphql.go
File metadata and controls
63 lines (51 loc) · 1.75 KB
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
// SPDX-License-Identifier: EUPL-1.2
package api
import (
"net/http"
"github.com/99designs/gqlgen/graphql"
"github.com/99designs/gqlgen/graphql/handler"
"github.com/99designs/gqlgen/graphql/playground"
"github.com/gin-gonic/gin"
)
// defaultGraphQLPath is the URL path where the GraphQL endpoint is mounted.
const defaultGraphQLPath = "/graphql"
// graphqlConfig holds configuration for the GraphQL endpoint.
type graphqlConfig struct {
schema graphql.ExecutableSchema
path string
playground bool
}
// GraphQLOption configures a GraphQL endpoint.
type GraphQLOption func(*graphqlConfig)
// WithPlayground enables the GraphQL Playground UI at {path}/playground.
func WithPlayground() GraphQLOption {
return func(cfg *graphqlConfig) {
cfg.playground = true
}
}
// WithGraphQLPath sets a custom URL path for the GraphQL endpoint.
// The default path is "/graphql".
func WithGraphQLPath(path string) GraphQLOption {
return func(cfg *graphqlConfig) {
cfg.path = path
}
}
// mountGraphQL registers the GraphQL handler and optional playground on the Gin engine.
func mountGraphQL(r *gin.Engine, cfg *graphqlConfig) {
srv := handler.NewDefaultServer(cfg.schema)
graphqlHandler := gin.WrapH(srv)
// Mount the GraphQL endpoint for all HTTP methods (POST for queries/mutations,
// GET for playground redirects and introspection).
r.Any(cfg.path, graphqlHandler)
if cfg.playground {
playgroundPath := cfg.path + "/playground"
playgroundHandler := playground.Handler("GraphQL", cfg.path)
r.GET(playgroundPath, wrapHTTPHandler(playgroundHandler))
}
}
// wrapHTTPHandler adapts a standard http.Handler to a Gin handler function.
func wrapHTTPHandler(h http.Handler) gin.HandlerFunc {
return func(c *gin.Context) {
h.ServeHTTP(c.Writer, c.Request)
}
}