router.go 1.5 KB
Newer Older
Y
Your Name 已提交
1 2 3 4 5 6
package httprouter

import (
	"net/http"

	"github.com/eolinker/goku-api-gateway/goku-node/common"
Y
Your Name 已提交
7
	"github.com/eolinker/goku-api-gateway/module/httprouter"
Y
Your Name 已提交
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
	"github.com/eolinker/goku-api-gateway/node/router"
)

//HTTPRouter httpRouter
type HTTPRouter struct {
}

//Factory factory
func Factory() router.Factory {
	return &HTTPRouter{}
}

//New new
func (*HTTPRouter) New() router.APIRouter {
	return new(Engine)
}

//Engine engine
type Engine struct {
	router httprouter.Router
}

//AddRouter addRouter
func (r *Engine) AddRouter(method, path string, router router.IRouter) {
Y
Your Name 已提交
32

Y
Your Name 已提交
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
	r.router.Handle(method, path,
		func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
			ctx := ContextFromRequest(req)
			ctx.RestfulParam = make(map[string]string)
			for _, param := range params {

				ctx.RestfulParam[param.Key] = param.Value
			}
			router.Router(ctx)
		})
}

//HandleFunc handleFunc
func (r *Engine) HandleFunc(method, path string, handler router.HandleFunc) {
	r.router.Handle(method, path, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
		ctx := ContextFromRequest(req)
		handler(ctx)
	})

}

func (r *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request, ctx *common.Context) {

	req = SetContextToRequest(req, ctx)

	r.router.ServeHTTP(w, req)
}

//AddNotFound addNotFound
func (r *Engine) AddNotFound(handler router.HandleFunc) {

	r.router.NotFound = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		ctx := ContextFromRequest(req)
		handler(ctx)
	})

}