AFAIRE
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
kong/router/router.go

62 lines
1.4 KiB

/*
------------------------------------------------------------------------------------------------------------------------
####### kong ####### Copyright (c) 2021-2022 losyme ################################################ MIT License #######
------------------------------------------------------------------------------------------------------------------------
*/
package router
import (
"net/http"
"strings"
"forge.chapril.org/losyme/errors"
"forge.chapril.org/losyme/kong/context"
)
type HandlerFunc func(*context.Context) error
type Router struct {
*SubRouter
srMap map[string]*SubRouter
}
func New(rrt context.RendererType) *Router {
return &Router{
SubRouter: newSubRouter(rrt),
}
}
func (r *Router) NewSubRouter(prefix string, rrt context.RendererType) (*SubRouter, error) {
if r.srMap == nil {
r.srMap = make(map[string]*SubRouter)
}
_, ok := r.srMap[prefix]
if ok {
return nil, errors.New("this subrouter already exists", "prefix", prefix) //////////////////////////////////////
}
sr := newSubRouter(rrt)
r.srMap[prefix] = sr
return sr, nil
}
func (r *Router) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
path := req.URL.Path
for prefix, sr := range r.srMap {
if strings.HasPrefix(path, prefix) {
sr.ServeHTTP(rw, req)
return
}
}
r.SubRouter.ServeHTTP(rw, req)
}
/*
######################################################################################################## @(°_°)@ #######
*/