1
0
mirror of https://github.com/labstack/echo.git synced 2025-01-01 22:09:21 +02:00
echo/route.go

183 lines
4.1 KiB
Go
Raw Normal View History

WIP: logger examples WIP: make default logger implemented custom writer for jsonlike logs WIP: improve examples WIP: defaultErrorHandler use errors.As to unwrap errors. Update readme WIP: default logger logs json, restore e.Start method WIP: clean router.Match a bit WIP: func types/fields have echo.Context has first element WIP: remove yaml tags as functions etc can not be serialized anyway WIP: change BindPathParams,BindQueryParams,BindHeaders from methods to functions and reverse arguments to be like DefaultBinder.Bind is WIP: improved comments, logger now extracts status from error WIP: go mod tidy WIP: rebase with 4.5.0 WIP: * removed todos. * removed StartAutoTLS and StartH2CServer methods from `StartConfig` * KeyAuth middleware errorhandler can swallow the error and resume next middleware WIP: add RouterConfig.UseEscapedPathForMatching to use escaped path for matching request against routes WIP: FIXMEs WIP: upgrade golang-jwt/jwt to `v4` WIP: refactor http methods to return RouteInfo WIP: refactor static not creating multiple routes WIP: refactor route and middleware adding functions not to return error directly WIP: Use 401 for problematic/missing headers for key auth and JWT middleware (#1552, #1402). > In summary, a 401 Unauthorized response should be used for missing or bad authentication WIP: replace `HTTPError.SetInternal` with `HTTPError.WithInternal` so we could not mutate global error variables WIP: add RouteInfo and RouteMatchType into Context what we could know from in middleware what route was matched and/or type of that match (200/404/405) WIP: make notFoundHandler and methodNotAllowedHandler private. encourage that all errors be handled in Echo.HTTPErrorHandler WIP: server cleanup ideas WIP: routable.ForGroup WIP: note about logger middleware WIP: bind should not default values on second try. use crypto rand for better randomness WIP: router add route as interface and returns info as interface WIP: improve flaky test (remains still flaky) WIP: add notes about bind default values WIP: every route can have their own path params names WIP: routerCreator and different tests WIP: different things WIP: remove route implementation WIP: support custom method types WIP: extractor tests WIP: v5.0.x proposal over v4.4.0
2021-07-15 22:34:01 +02:00
package echo
import (
"bytes"
"errors"
"fmt"
"reflect"
"runtime"
)
// Route contains information to adding/registering new route with the router.
// Method+Path pair uniquely identifies the Route. It is mandatory to provide Method+Path+Handler fields.
type Route struct {
Method string
Path string
Handler HandlerFunc
Middlewares []MiddlewareFunc
Name string
}
// ToRouteInfo converts Route to RouteInfo
func (r Route) ToRouteInfo(params []string) RouteInfo {
name := r.Name
if name == "" {
name = r.Method + ":" + r.Path
}
return routeInfo{
method: r.Method,
path: r.Path,
params: append([]string(nil), params...),
name: name,
}
}
// ToRoute returns Route which Router uses to register the method handler for path.
func (r Route) ToRoute() Route {
return r
}
// ForGroup recreates Route with added group prefix and group middlewares it is grouped to.
func (r Route) ForGroup(pathPrefix string, middlewares []MiddlewareFunc) Routable {
r.Path = pathPrefix + r.Path
if len(middlewares) > 0 {
m := make([]MiddlewareFunc, 0, len(middlewares)+len(r.Middlewares))
m = append(m, middlewares...)
m = append(m, r.Middlewares...)
r.Middlewares = m
}
return r
}
type routeInfo struct {
method string
path string
params []string
name string
}
func (r routeInfo) Method() string {
return r.method
}
func (r routeInfo) Path() string {
return r.path
}
func (r routeInfo) Params() []string {
return append([]string(nil), r.params...)
}
func (r routeInfo) Name() string {
return r.name
}
// Reverse reverses route to URL string by replacing path parameters with given params values.
func (r routeInfo) Reverse(params ...interface{}) string {
uri := new(bytes.Buffer)
ln := len(params)
n := 0
for i, l := 0, len(r.path); i < l; i++ {
if (r.path[i] == paramLabel || r.path[i] == anyLabel) && n < ln {
for ; i < l && r.path[i] != '/'; i++ {
}
uri.WriteString(fmt.Sprintf("%v", params[n]))
n++
}
if i < l {
uri.WriteByte(r.path[i])
}
}
return uri.String()
}
// HandlerName returns string name for given function.
func HandlerName(h HandlerFunc) string {
t := reflect.ValueOf(h).Type()
if t.Kind() == reflect.Func {
return runtime.FuncForPC(reflect.ValueOf(h).Pointer()).Name()
}
return t.String()
}
// Reverse reverses route to URL string by replacing path parameters with given params values.
func (r Routes) Reverse(name string, params ...interface{}) (string, error) {
for _, rr := range r {
if rr.Name() == name {
return rr.Reverse(params...), nil
}
}
return "", errors.New("route not found")
}
// FindByMethodPath searched for matching route info by method and path
func (r Routes) FindByMethodPath(method string, path string) (RouteInfo, error) {
if r == nil {
return nil, errors.New("route not found by method and path")
}
for _, rr := range r {
if rr.Method() == method && rr.Path() == path {
return rr, nil
}
}
return nil, errors.New("route not found by method and path")
}
// FilterByMethod searched for matching route info by method
func (r Routes) FilterByMethod(method string) (Routes, error) {
if r == nil {
return nil, errors.New("route not found by method")
}
result := make(Routes, 0)
for _, rr := range r {
if rr.Method() == method {
result = append(result, rr)
}
}
if len(result) == 0 {
return nil, errors.New("route not found by method")
}
return result, nil
}
// FilterByPath searched for matching route info by path
func (r Routes) FilterByPath(path string) (Routes, error) {
if r == nil {
return nil, errors.New("route not found by path")
}
result := make(Routes, 0)
for _, rr := range r {
if rr.Path() == path {
result = append(result, rr)
}
}
if len(result) == 0 {
return nil, errors.New("route not found by path")
}
return result, nil
}
// FilterByName searched for matching route info by name
func (r Routes) FilterByName(name string) (Routes, error) {
if r == nil {
return nil, errors.New("route not found by name")
}
result := make(Routes, 0)
for _, rr := range r {
if rr.Name() == name {
result = append(result, rr)
}
}
if len(result) == 0 {
return nil, errors.New("route not found by name")
}
return result, nil
}