-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
75 lines (61 loc) · 1.54 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
package switchboard
import (
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
)
func NewServer(path string, port int, reload bool) (*http.Server, error) {
log.Printf("reading config at path %s", path)
config, err := ReadConfig(path)
if err != nil {
return nil, fmt.Errorf("error reading config: %s", err)
}
var router http.Handler
if !reload {
router, err = BuildRouter(config)
if err != nil {
return nil, fmt.Errorf("error building routes: %s", err)
}
} else {
router, err = BuildReloadRouter(path)
if err != nil {
return nil, fmt.Errorf("error building routes: %s", err)
}
}
return &http.Server{
Addr: fmt.Sprintf(":%d", port),
Handler: router,
}, nil
}
func BuildRouter(config *Config) (http.Handler, error) {
router := mux.NewRouter()
route := &RootRoute{Routes: config.Routes}
err := route.AttachHandlers(router, Pipeline{})
if err != nil {
return nil, err
}
return router, nil
}
func BuildReloadRouter(path string) (http.Handler, error) {
log.Printf("watching config at path %s", path)
_, err := ReadConfig(path)
if err != nil {
return nil, fmt.Errorf("error reading config: %s", err)
}
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("reloading config at path %s", path)
config, err := ReadConfig(path)
if err != nil {
log.Printf("error rereading config: %s", err)
return
}
router, err := BuildRouter(config)
if err != nil {
log.Printf("error rebuilding routes: %s", err)
return
}
router.ServeHTTP(w, r)
})
return handler, nil
}