/
server.go
108 lines (88 loc) · 2.5 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
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
package server
import (
"fmt"
"net"
"net/http"
log "github.com/Sirupsen/logrus"
"github.com/rs/cors"
"github.com/urfave/negroni"
"github.com/danielkrainas/csense/api/server/handlers"
"github.com/danielkrainas/csense/configuration"
"github.com/danielkrainas/csense/context"
)
type Server struct {
config *configuration.Config
app *handlers.App
server *http.Server
}
func New(ctx context.Context, config *configuration.Config) (*Server, error) {
app, err := handlers.NewApp(ctx, config)
if err != nil {
return nil, fmt.Errorf("error creating server app: %v", err)
}
handler := alive("/", app)
handler = panicHandler(handler)
handler = contextHandler(app, handler)
handler = loggingHandler(app, handler)
n := negroni.New()
n.Use(cors.New(cors.Options{
AllowedOrigins: config.HTTP.CORS.Origins,
AllowedMethods: config.HTTP.CORS.Methods,
AllowCredentials: true,
AllowedHeaders: config.HTTP.CORS.Headers,
Debug: config.HTTP.CORS.Debug,
}))
n.UseHandler(handler)
s := &Server{
app: app,
config: config,
server: &http.Server{
Addr: config.HTTP.Addr,
Handler: n,
},
}
return s, nil
}
func (server *Server) ListenAndServe() error {
config := server.config
ln, err := net.Listen("tcp", config.HTTP.Addr)
if err != nil {
return err
}
context.GetLogger(server.app).Infof("listening on %v", ln.Addr())
return server.server.Serve(ln)
}
func panicHandler(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
log.Panicf("%v", err)
}
}()
handler.ServeHTTP(w, r)
})
}
func alive(path string, handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == path {
w.Header().Set("Cache-Control", "no-cache")
w.WriteHeader(http.StatusOK)
return
}
handler.ServeHTTP(w, r)
})
}
func contextHandler(parent context.Context, handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := context.DefaultContextManager.Context(parent, w, r)
defer context.DefaultContextManager.Release(ctx)
handler.ServeHTTP(w, r)
})
}
func loggingHandler(parent context.Context, handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := context.DefaultContextManager.Context(parent, w, r)
context.GetRequestLogger(ctx).Info("request started")
handler.ServeHTTP(w, r)
})
}