-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathserver.go
More file actions
100 lines (84 loc) · 2.32 KB
/
server.go
File metadata and controls
100 lines (84 loc) · 2.32 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
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
package main
import (
"context"
_ "embed"
"log"
"net/http"
"time"
graphql "github.com/graph-gophers/graphql-go"
"github.com/graph-gophers/graphql-go/relay"
graphqlws "github.com/graph-gophers/graphql-transport-ws"
)
var (
//go:embed index.html
graphiqlHTML []byte
//go:embed schema.graphql
schemaSDL string
)
type resolver struct{}
type queryResolver struct{}
type subscriptionResolver struct{}
type tickResolver struct {
at string
number int32
}
func (*resolver) Query() *queryResolver { return &queryResolver{} }
func (*resolver) Subscription() *subscriptionResolver { return &subscriptionResolver{} }
func (*queryResolver) Hello() string { return "Hello from graphql-transport-ws!" }
func (*subscriptionResolver) Ticks(ctx context.Context, args struct{ Count *int32 }) <-chan *tickResolver {
limit := int32(10)
if args.Count != nil && *args.Count > 0 {
limit = *args.Count
}
ch := make(chan *tickResolver)
go func() {
defer close(ch)
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
var n int32
for {
select {
case <-ctx.Done():
return
case t := <-ticker.C:
n++
tick := &tickResolver{at: t.UTC().Format(time.RFC3339), number: n}
select {
case <-ctx.Done():
return
case ch <- tick:
}
if n >= limit {
return
}
}
}
}()
return ch
}
func (r *tickResolver) At() string { return r.at }
func (r *tickResolver) Number() int32 { return r.number }
func main() {
schema := graphql.MustParseSchema(schemaSDL, &resolver{}, graphql.UseStringDescriptions())
mux := http.NewServeMux()
// GraphiQL UI
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
if r.Method != http.MethodGet {
w.Header().Set("Allow", http.MethodGet)
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write(graphiqlHTML)
})
// GraphQL endpoint — handles both HTTP POST and WebSocket (graphql-transport-ws)
mux.Handle("/graphql", graphqlws.NewHandlerFunc(schema, &relay.Handler{Schema: schema}))
addr := ":8080"
log.Printf("GraphQL -> http://localhost%s/graphql", addr)
log.Printf("GraphiQL -> http://localhost%s/", addr)
log.Fatal(http.ListenAndServe(addr, mux))
}