-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.go
220 lines (187 loc) · 5.65 KB
/
main.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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
package main
import (
"context"
"fmt"
"html/template"
"math/rand"
"net/http"
"os"
"strconv"
"time"
graphql "github.com/graph-gophers/graphql-go"
"github.com/graph-gophers/graphql-go/relay"
"github.com/graph-gophers/graphql-transport-ws/graphqlws"
)
const schema = `
schema {
subscription: Subscription
mutation: Mutation
query: Query
}
type Query {
hello: String!
}
type Subscription {
helloSaid(): HelloSaidEvent!
}
type Mutation {
sayHello(msg: String!): HelloSaidEvent!
}
type HelloSaidEvent {
id: String!
msg: String!
}
`
var httpPort = 8080
func init() {
port := os.Getenv("HTTP_PORT")
if port != "" {
var err error
httpPort, err = strconv.Atoi(port)
if err != nil {
panic(err)
}
}
}
func main() {
// graphiql handler
http.HandleFunc("/", http.HandlerFunc(graphiql))
// init graphQL schema
s, err := graphql.ParseSchema(schema, newResolver())
if err != nil {
panic(err)
}
// graphQL handler
graphQLHandler := graphqlws.NewHandlerFunc(s, &relay.Handler{Schema: s})
http.HandleFunc("/graphql", graphQLHandler)
// start HTTP server
if err := http.ListenAndServe(fmt.Sprintf(":%d", httpPort), nil); err != nil {
panic(err)
}
}
type resolver struct {
helloSaidEvents chan *helloSaidEvent
helloSaidSubscriber chan *helloSaidSubscriber
}
func newResolver() *resolver {
r := &resolver{
helloSaidEvents: make(chan *helloSaidEvent),
helloSaidSubscriber: make(chan *helloSaidSubscriber),
}
go r.broadcastHelloSaid()
return r
}
func (r *resolver) Hello() string {
return "Hello world!"
}
func (r *resolver) SayHello(args struct{ Msg string }) *helloSaidEvent {
e := &helloSaidEvent{msg: args.Msg, id: randomID()}
go func() {
select {
case r.helloSaidEvents <- e:
case <-time.After(1 * time.Second):
}
}()
return e
}
type helloSaidSubscriber struct {
stop <-chan struct{}
events chan<- *helloSaidEvent
}
func (r *resolver) broadcastHelloSaid() {
subscribers := map[string]*helloSaidSubscriber{}
unsubscribe := make(chan string)
// NOTE: subscribing and sending events are at odds.
for {
select {
case id := <-unsubscribe:
delete(subscribers, id)
case s := <-r.helloSaidSubscriber:
subscribers[randomID()] = s
case e := <-r.helloSaidEvents:
for id, s := range subscribers {
go func(id string, s *helloSaidSubscriber) {
select {
case <-s.stop:
unsubscribe <- id
return
default:
}
select {
case <-s.stop:
unsubscribe <- id
case s.events <- e:
case <-time.After(time.Second):
}
}(id, s)
}
}
}
}
func (r *resolver) HelloSaid(ctx context.Context) <-chan *helloSaidEvent {
c := make(chan *helloSaidEvent)
// NOTE: this could take a while
r.helloSaidSubscriber <- &helloSaidSubscriber{events: c, stop: ctx.Done()}
return c
}
type helloSaidEvent struct {
id string
msg string
}
func (r *helloSaidEvent) Msg() string {
return r.msg
}
func (r *helloSaidEvent) ID() string {
return r.id
}
func randomID() string {
var letter = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
b := make([]rune, 16)
for i := range b {
b[i] = letter[rand.Intn(len(letter))]
}
return string(b)
}
var graphiql = func(w http.ResponseWriter, r *http.Request) {
t := template.Must(template.New("graphiql").Parse(`
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/graphiql/0.11.10/graphiql.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/1.1.0/fetch.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.5.4/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.5.4/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/graphiql/0.11.10/graphiql.js"></script>
<script src="//unpkg.com/subscriptions-transport-ws@0.8.3/browser/client.js"></script>
<script src="//unpkg.com/graphiql-subscriptions-fetcher@0.0.2/browser/client.js"></script>
</head>
<body style="width: 100%; height: 100%; margin: 0; overflow: hidden;">
<div id="graphiql" style="height: 100vh;">Loading...</div>
<script>
function graphQLFetcher(graphQLParams) {
return fetch("/graphql", {
method: "post",
body: JSON.stringify(graphQLParams),
credentials: "include",
}).then(function (response) {
return response.text();
}).then(function (responseBody) {
try {
return JSON.parse(responseBody);
} catch (error) {
return responseBody;
}
});
}
var subscriptionsClient = new window.SubscriptionsTransportWs.SubscriptionClient('ws://localhost:{{ . }}/graphql', { reconnect: true });
var subscriptionsFetcher = window.GraphiQLSubscriptionsFetcher.graphQLFetcher(subscriptionsClient, graphQLFetcher);
ReactDOM.render(
React.createElement(GraphiQL, {fetcher: subscriptionsFetcher}),
document.getElementById("graphiql")
);
</script>
</body>
</html>
`))
t.Execute(w, httpPort)
}