1
0
mirror of https://github.com/kataras/iris.git synced 2026-01-07 20:17:05 +00:00

example: write our own customized router using the high-level API which gives access to the correct context and routes

Former-commit-id: d2369c20490619cad0dd6f7b6ed01cdbef51a853
This commit is contained in:
Gerasimos (Makis) Maropoulos
2018-10-02 06:36:51 +03:00
parent 97e96ed6ca
commit 120b5fb635
9 changed files with 138 additions and 27 deletions

View File

@@ -17,10 +17,9 @@ import (
// RequestHandler the middle man between acquiring a context and releasing it.
// By-default is the router algorithm.
type RequestHandler interface {
// HandleRequest is same as context.Handler but its usage is only about routing,
// separate the concept here.
// HandleRequest should handle the request based on the Context.
HandleRequest(context.Context)
// Build should builds the handler, it's being called on router's BuildRouter.
// Build should builds the handler, it's being called on router's BuildRouter.
Build(provider RoutesProvider) error
// RouteExists reports whether a particular route exists.
RouteExists(ctx context.Context, method, path string) bool

View File

@@ -31,7 +31,7 @@ func NewRouter() *Router { return &Router{} }
// RefreshRouter re-builds the router. Should be called when a route's state
// changed (i.e Method changed at serve-time).
func (router *Router) RefreshRouter() error {
return router.BuildRouter(router.cPool, router.requestHandler, router.routesProvider)
return router.BuildRouter(router.cPool, router.requestHandler, router.routesProvider, true)
}
// BuildRouter builds the router based on
@@ -41,7 +41,7 @@ func (router *Router) RefreshRouter() error {
// its wrapper.
//
// Use of RefreshRouter to re-build the router if needed.
func (router *Router) BuildRouter(cPool *context.Pool, requestHandler RequestHandler, routesProvider RoutesProvider) error {
func (router *Router) BuildRouter(cPool *context.Pool, requestHandler RequestHandler, routesProvider RoutesProvider, force bool) error {
if requestHandler == nil {
return errors.New("router: request handler is nil")
@@ -60,9 +60,23 @@ func (router *Router) BuildRouter(cPool *context.Pool, requestHandler RequestHan
defer router.mu.Unlock()
// store these for RefreshRouter's needs.
router.cPool = cPool
router.requestHandler = requestHandler
router.routesProvider = routesProvider
if force {
router.cPool = cPool
router.requestHandler = requestHandler
router.routesProvider = routesProvider
} else {
if router.cPool == nil {
router.cPool = cPool
}
if router.requestHandler == nil {
router.requestHandler = requestHandler
}
if router.routesProvider == nil && routesProvider != nil {
router.routesProvider = routesProvider
}
}
// the important
router.mainHandler = func(w http.ResponseWriter, r *http.Request) {