forked from EconomistDigitalSolutions/goberry
/
router.go
75 lines (67 loc) · 1.82 KB
/
router.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 main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"github.com/EconomistDigitalSolutions/ramlapi"
"github.com/EconomistDigitalSolutions/watchman/journal"
"github.com/buddhamagnet/raml"
"github.com/buddhamagnet/yaml"
"github.com/gorilla/mux"
)
var router *mux.Router
var api *raml.APIDefinition
// NewRouter creates a mux router, sets up
// a static handler and registers the dynamic
// routes and middleware handlers with the mux.
func NewRouter(ramlFile string) *mux.Router {
router = mux.NewRouter().StrictSlash(true)
// Assemble middleware as required.
assembleMiddleware(router)
assembleRoutes(router, ramlFile)
return router
}
// assembleMiddleware sets up the middleware stack.
func assembleMiddleware(r *mux.Router) {
http.Handle("/",
JSONMiddleware(
LoggingMiddleware(
RecoverMiddleware(r))))
}
func assembleRoutes(r *mux.Router, f string) {
var err error
// If bundling is enabled, read the RAML
// from bundle.go
if os.Getenv("BUNDLE_ASSETS") != "" {
bundle, _ := MainBundle.Open("api.raml")
data, _ := ioutil.ReadAll(bundle)
err = yaml.Unmarshal(data, &api)
if err != nil {
log.Fatal(err)
}
// Otherwise, read the file from the filesystem.
} else {
api, err = ramlapi.ProcessRAML(f)
if err != nil {
log.Fatal(err)
}
}
journal.LogChannel("raml-processor", fmt.Sprintf("processing API spec for %s", api.Title))
journal.LogChannel("raml-processor", fmt.Sprintf("base URI at %s", api.BaseUri))
ramlapi.Build(api, routerFunc)
}
func routerFunc(data map[string]string) {
route := router.
Methods(data["verb"]).
Path(data["path"]).
Handler(RouteMap[data["handler"]])
if data["query"] != "" {
if data["query_pattern"] != "" {
route.Queries(data["query"], fmt.Sprintf("{%s:%s}", data["query"], data["query_pattern"]))
} else {
route.Queries(data["query"], "")
}
}
}