Skip to content
Permalink
master
Switch branches/tags
Go to file
 
 
Cannot retrieve contributors at this time
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"], "")
}
}
}