forked from wundergraph/graphql-go-tools
/
handler.go
82 lines (67 loc) · 1.96 KB
/
handler.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
package graph
import (
"context"
"encoding/json"
"net/http"
"time"
"github.com/99designs/gqlgen/graphql/handler"
"github.com/99designs/gqlgen/graphql/handler/debug"
"github.com/99designs/gqlgen/graphql/handler/extension"
"github.com/99designs/gqlgen/graphql/handler/transport"
"github.com/gorilla/websocket"
"go.uber.org/atomic"
"github.com/matthewmcneely/graphql-go-tools/v2/pkg/testing/federationtesting/products/graph/generated"
)
var websocketConnections atomic.Uint32
type EndpointOptions struct {
EnableDebug bool
EnableRandomness bool
OverrideUpdateInterval time.Duration
}
var TestOptions = EndpointOptions{
EnableDebug: false,
EnableRandomness: false,
OverrideUpdateInterval: 50 * time.Millisecond,
}
func GraphQLEndpointHandler(opts EndpointOptions) http.Handler {
websocketConnections.Store(0)
srv := handler.New(generated.NewExecutableSchema(generated.Config{Resolvers: &Resolver{}}))
srv.AddTransport(transport.POST{})
srv.AddTransport(transport.Websocket{
KeepAlivePingInterval: 10 * time.Second,
Upgrader: websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
},
InitFunc: func(ctx context.Context, _ transport.InitPayload) (context.Context, error) {
websocketConnections.Inc()
go func(ctx context.Context) {
<-ctx.Done()
websocketConnections.Dec()
}(ctx)
return ctx, nil
},
})
srv.Use(extension.Introspection{})
if opts.EnableDebug {
srv.Use(&debug.Tracer{})
}
randomnessEnabled = opts.EnableRandomness
if opts.OverrideUpdateInterval > 0 {
updateInterval = opts.OverrideUpdateInterval
}
return srv
}
func WebsocketConnectionsHandler(w http.ResponseWriter, r *http.Request) {
response := map[string]uint32{
"websocket_connections": websocketConnections.Load(),
}
responseBytes, err := json.Marshal(response)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte("error"))
return
}
_, _ = w.Write(responseBytes)
}