/
http.go
106 lines (86 loc) · 2.06 KB
/
http.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
package http
import (
"context"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/ganiszulfa/concise/backend/internal/gql"
"github.com/ganiszulfa/concise/backend/internal/middleware"
"github.com/ganiszulfa/concise/backend/pkg/trace"
"github.com/graphql-go/graphql"
"github.com/graphql-go/handler"
log "github.com/sirupsen/logrus"
"gorm.io/gorm"
)
var graphQL *handler.Handler
func Serve() {
trace.Func()
schema, err := graphql.NewSchema(
graphql.SchemaConfig{
Query: gql.QueryType,
Mutation: gql.MutationType,
},
)
if err != nil {
panic(err)
}
graphQL = handler.New(&handler.Config{
Schema: &schema,
Pretty: true,
GraphiQL: true,
ResultCallbackFn: resultCallback,
})
http.HandleFunc("/health", healthHandler)
http.HandleFunc("/graphql", middleware.Authorize(gqlHandler))
address := ":8080"
srv := &http.Server{
Addr: address,
Handler: http.DefaultServeMux,
}
done := make(chan os.Signal, 1)
signal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
log.Infof("running HTTP server in localhost%s", address)
go func() {
if err := srv.ListenAndServe(); err != nil {
log.Error(err)
}
}()
<-done
log.Info("HTTP server is shutting down..")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Fatalf("Server shutdown failed: %+v", err)
}
log.Info("Server shutdown properly.")
}
func resultCallback(
ctx context.Context,
params *graphql.Params,
result *graphql.Result,
responseBody []byte,
) {
trace.Func()
if result.Errors != nil {
for _, e := range result.Errors {
if e.Message != gorm.ErrRecordNotFound.Error() {
log.Error(e.Message, " > ", e.Path)
} else {
log.Debug(e.Message, " > ", e.Path)
}
}
}
}
func healthHandler(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(http.StatusOK)
_, err := w.Write([]byte("ok"))
if err != nil {
log.Error(err)
}
}
func gqlHandler(w http.ResponseWriter, req *http.Request) {
trace.Func()
graphQL.ServeHTTP(w, req)
}