-
Notifications
You must be signed in to change notification settings - Fork 77
/
server.go
75 lines (61 loc) · 1.99 KB
/
server.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
// Command graphql-go-example starts an HTTP GraphQL API server which is backed by data
// against the https://swapi.co REST API.
package main
import (
"log"
"net/http"
"time"
graphql "github.com/graph-gophers/graphql-go"
"github.com/tonyghita/graphql-go-example/handler"
"github.com/tonyghita/graphql-go-example/loader"
"github.com/tonyghita/graphql-go-example/resolver"
"github.com/tonyghita/graphql-go-example/schema"
"github.com/tonyghita/graphql-go-example/swapi"
)
func main() {
// Tweak configuration values here.
var (
addr = ":8000"
readHeaderTimeout = 1 * time.Second
writeTimeout = 10 * time.Second
idleTimeout = 90 * time.Second
maxHeaderBytes = http.DefaultMaxHeaderBytes
)
log.SetFlags(log.Lshortfile | log.LstdFlags)
c := swapi.NewClient(http.DefaultClient) // TODO: don't use the default client.
root, err := resolver.NewRoot(c)
if err != nil {
log.Fatalf("creating root resolver: %s", err)
}
s, err := schema.String()
if err != nil {
log.Fatalf("reading embedded schema contents: %s", err)
}
// Create the request handler; inject dependencies.
h := handler.GraphQL{
// Parse and validate schema. Panic if unable to do so.
Schema: graphql.MustParseSchema(s, root),
Loaders: loader.Initialize(c),
}
// Register handlers to routes.
mux := http.NewServeMux()
mux.Handle("/", handler.GraphiQL{})
mux.Handle("/graphql/", h)
mux.Handle("/graphql", h) // Register without a trailing slash to avoid redirect.
// Configure the HTTP server.
srv := &http.Server{
Addr: addr,
Handler: mux,
ReadHeaderTimeout: readHeaderTimeout,
WriteTimeout: writeTimeout,
IdleTimeout: idleTimeout,
MaxHeaderBytes: maxHeaderBytes,
}
// Begin listeing for requests.
log.Printf("Listening for requests on %s", srv.Addr)
if err = srv.ListenAndServe(); err != nil {
log.Println("server.ListenAndServe:", err)
}
// TODO: intercept shutdown signals for cleanup of connections.
log.Println("Shut down.")
}