File: httprouter.go

package info (click to toggle)
golang-github-manyminds-api2go 1.0-RC4-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 552 kB
  • sloc: sh: 23; makefile: 3
file content (53 lines) | stat: -rw-r--r-- 1,529 bytes parent folder | download | duplicates (3)
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
package routing

import (
	"net/http"

	"github.com/julienschmidt/httprouter"
)

// HTTPRouter default router implementation for api2go
type HTTPRouter struct {
	router *httprouter.Router
}

// Handle each method like before and wrap them into julienschmidt handler func style
func (h HTTPRouter) Handle(protocol, route string, handler HandlerFunc) {
	wrappedCallback := func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		params := map[string]string{}
		for _, p := range ps {
			params[p.Key] = p.Value
		}

		handler(w, r, params)
	}

	h.router.Handle(protocol, route, wrappedCallback)
}

// Handler returns the router
func (h HTTPRouter) Handler() http.Handler {
	return h.router
}

// SetRedirectTrailingSlash wraps this internal functionality of
// the julienschmidt router.
func (h *HTTPRouter) SetRedirectTrailingSlash(enabled bool) {
	h.router.RedirectTrailingSlash = enabled
}

// GetRouteParameter implemention will extract the param the julienschmidt way
func (h HTTPRouter) GetRouteParameter(r http.Request, param string) string {
	path := httprouter.CleanPath(r.URL.Path)
	_, params, _ := h.router.Lookup(r.Method, path)
	return params.ByName(param)
}

// NewHTTPRouter returns a new instance of julienschmidt/httprouter
// this is the default router when using api2go
func NewHTTPRouter(prefix string, notAllowedHandler http.Handler) Routeable {
	router := httprouter.New()
	router.HandleMethodNotAllowed = true
	router.MethodNotAllowed = notAllowedHandler
	return &HTTPRouter{router: router}
}