-
Notifications
You must be signed in to change notification settings - Fork 0
/
baseRouter.go
69 lines (57 loc) · 1.78 KB
/
baseRouter.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
package server
import (
"bytes"
"io"
"io/ioutil"
"net/http"
"strings"
"github.com/GeertJohan/go.rice"
"github.com/go-chi/chi/middleware"
"github.com/gorilla/mux"
"github.com/pkg/errors"
)
const (
swaggerBoxName = "swagger"
swaggerFileName = "swagger.yaml"
)
// NewBaseRouter will return new router with already registered standard endpoints
// /swagger/swagger.yaml - to serve swagger schema
// /version.json - to serve service version
// /{profilerPath}/ - to serve http profiler
func NewBaseRouter(h BaseHTTPHandler, serviceVersion, profilerPath string) (*mux.Router, error) {
srv := mux.NewRouter()
// SWAGGER
box, err := rice.FindBox(swaggerBoxName)
if err != nil {
return nil, errors.Wrap(err, "failed to find box for "+swaggerBoxName)
}
file, err := box.Open(swaggerFileName)
if err != nil {
return nil, errors.Wrap(err, "failed to open "+swaggerFileName)
}
APIDefinition, err := ioutil.ReadAll(file)
if err != nil {
return nil, errors.Wrap(err, "failed to read api definition")
}
// Register swagger handler
srv.HandleFunc(strings.Join([]string{"", swaggerBoxName, swaggerFileName}, "/"), func(w http.ResponseWriter, r *http.Request) {
l := h.NewLoggingResponseWriter(w, r)
_, err := io.Copy(w, bytes.NewReader(APIDefinition))
if err != nil {
l.WriteHeaderWithErr(http.StatusInternalServerError, err)
}
})
// VERSION
versionResp := []byte(`{"version":"` + serviceVersion + `"}`)
srv.HandleFunc("/version.json", func(w http.ResponseWriter, r *http.Request) {
l := h.NewLoggingResponseWriter(w, r)
w.Header().Set("Content-Type", "application/json")
_, err := w.Write(versionResp)
if err != nil {
l.WriteHeaderWithErr(http.StatusInternalServerError, err)
}
})
// HTTP PROFILER
srv.Handle(profilerPath, middleware.Profiler())
return srv, nil
}