grouter

package
v0.0.0-...-3e416e1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 19, 2024 License: MIT Imports: 13 Imported by: 0

README

GMC HTTP Router

this package based on http://github.com/julienschmidt/httprouter, if you using this package code, you should comply with it's LICENSE.

Documentation

Overview

Package grouter is a trie based high performance HTTP request router.

A trivial example is:

package main

import (
    "fmt"
    "github.com/julienschmidt/httprouter"
    "net/http"
    "log"
)

func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
    fmt.Fprint(w, "Welcome!\n")
}

func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
    fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
}

func main() {
    router := httprouter.New()
    router.GET("/", Index)
    router.GET("/hello/:name", Hello)

    log.Fatal(http.ListenAndServe(":8080", router))
}

The router matches incoming requests by the request method and the path. If a handle is registered for this path and method, the router delegates the request to that function. For the methods GET, POST, PUT, PATCH, DELETE and OPTIONS shortcut functions exist to register handles, for all other methods router.Handle can be used.

The registered path, against which the router matches incoming requests, can contain two types of parameters:

Syntax    Type
:name     named parameter
*name     catch-all parameter

Named parameters are dynamic path segments. They match anything until the next '/' or the path end:

Path: /blog/:category/:post

Requests:
 /blog/go/request-routers            match: category="go", post="request-routers"
 /blog/go/request-routers/           no match, but the router would redirect
 /blog/go/                           no match
 /blog/go/request-routers/comments   no match

Catch-all parameters match anything until the path end, including the directory index (the '/' before the catch-all). Since they match anything until the end, catch-all parameters must always be the final path element.

Path: /files/*filepath

Requests:
 /files/                             match: filepath="/"
 /files/LICENSE                      match: filepath="/LICENSE"
 /files/templates/article.html       match: filepath="/templates/article.html"
 /files                              no match, but the router would redirect

The value of parameters is saved as a slice of the Param struct, consisting each of a key and a value. The slice is passed to the Handle func as a third parameter. There are two ways to retrieve the value of a parameter:

// by the name of the parameter
user := ps.ByName("user") // defined by :user or *user

// by the index of the parameter. This way you can also get the name (key)
thirdKey   := ps[2].Key   // the name of the 3rd parameter
thirdValue := ps[2].Value // the value of the 3rd parameter

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CleanPath

func CleanPath(p string) string

CleanPath is the URL version of path.Clean, it returns a canonical URL path for p, eliminating . and .. elements.

The following rules are applied iteratively until no further processing can be done:

  1. Replace multiple slashes with a single slash.
  2. Eliminate each . path name element (the current directory).
  3. Eliminate each inner .. path name element (the parent directory) along with the non-.. element that precedes it.
  4. Eliminate .. elements that begin a rooted path: that is, replace "/.." by "/" at the beginning of a path.

If the result of this process is an empty string, "/" is returned

Types

type HTTPRouter

type HTTPRouter struct {
	*Router
	// contains filtered or unexported fields
}

func NewHTTPRouter

func NewHTTPRouter(ctx gcore.Ctx) *HTTPRouter

func (*HTTPRouter) Controller

func (s *HTTPRouter) Controller(urlPath string, obj gcore.Controller, ext ...string)

Controller binds a controller's methods to router ext is method's extension in url.

func (*HTTPRouter) ControllerMethod

func (s *HTTPRouter) ControllerMethod(urlPath string, obj gcore.Controller, method string)

ControllerMethod binds a controller's method to router

func (*HTTPRouter) Ext

func (this *HTTPRouter) Ext(ext string)

Ext sets Controller()'s default ext

func (*HTTPRouter) Group

func (s *HTTPRouter) Group(ns string) gcore.HTTPRouter

Group create a group in namespace ns

func (*HTTPRouter) Handle

func (s *HTTPRouter) Handle(method, path string, handle gcore.Handle)

Handle registers a new request handle with the given path and method.

For GET, POST, PUT, PATCH and DELETE requests the respective shortcut functions can be used.

This function is intended for bulk loading and to allow the usage of less frequently used, non-standardized or custom methods (e.g. for internal communication with a proxy).

func (*HTTPRouter) HandleAny

func (s *HTTPRouter) HandleAny(path string, handle gcore.Handle)

HandleAny registers a new request handle with the given path and all http methods, GET, POST, PUT, PATCH, DELETE and OPTIONS

func (*HTTPRouter) Handler

func (s *HTTPRouter) Handler(method, path string, handler http.Handler)

Handler is an adapter which allows the usage of an http.Handler as a request handle. The Params are available in the request context under ParamsKey.

func (*HTTPRouter) HandlerAny

func (s *HTTPRouter) HandlerAny(path string, handler http.Handler)

HandlerAny is an adapter which allows the usage of an http.Handler as a request handle match all http methods, GET, POST, PUT, PATCH, DELETE and OPTIONS

func (*HTTPRouter) HandlerFunc

func (s *HTTPRouter) HandlerFunc(method, path string, handler http.HandlerFunc)

HandlerFunc is an adapter which allows the usage of an http.HandlerFunc as a request handle.

func (*HTTPRouter) HandlerFuncAny

func (s *HTTPRouter) HandlerFuncAny(path string, handler http.HandlerFunc)

HandlerFuncAny is an adapter which allows the usage of an http.HandlerFunc as a request handle match all http methods, GET, POST, PUT, PATCH, DELETE and OPTIONS

func (*HTTPRouter) Namespace

func (s *HTTPRouter) Namespace() string

func (*HTTPRouter) PrintRouteTable

func (s *HTTPRouter) PrintRouteTable(w io.Writer)

PrintRouteTable dump all routes into `w`, if `w` is nil, os.Stdout will be used.

func (*HTTPRouter) RouteTable

func (s *HTTPRouter) RouteTable() (table map[string][]string)

RouteTable returns all routes in router. KEY is url path, VALUE is http methods.

type Router

type Router struct {

	// If enabled, adds the matched route path onto the http.Request context
	// before invoking the handler.
	// The matched route path is only added to handlers of routes that were
	// registered when this option was enabled.
	SaveMatchedRoutePath bool

	// Enables automatic redirection if the current route can't be matched but a
	// handler for the path with (without) the trailing slash exists.
	// For example if /foo/ is requested but a route only exists for /foo, the
	// client is redirected to /foo with http status code 301 for GET requests
	// and 308 for all other request methods.
	RedirectTrailingSlash bool

	// If enabled, the router tries to fix the current request path, if no
	// handle is registered for it.
	// First superfluous path elements like ../ or // are removed.
	// Afterwards the router does a case-insensitive lookup of the cleaned path.
	// If a handle can be found for this route, the router makes a redirection
	// to the corrected path with status code 301 for GET requests and 308 for
	// all other request methods.
	// For example /FOO and /..//Foo could be redirected to /foo.
	// RedirectTrailingSlash is independent of this option.
	RedirectFixedPath bool

	// If enabled, the router checks if another method is allowed for the
	// current route, if the current request can not be routed.
	// If this is the case, the request is answered with 'Method Not Allowed'
	// and HTTP status code 405.
	// If no other Method is allowed, the request is delegated to the NotFound
	// handler.
	HandleMethodNotAllowed bool

	// If enabled, the router automatically replies to OPTIONS requests.
	// Custom OPTIONS handlers take priority over automatic replies.
	HandleOPTIONS bool

	// An optional http.Handler that is called on automatic OPTIONS requests.
	// The handler is only called if HandleOPTIONS is true and no OPTIONS
	// handler for the specific path was set.
	// The "Allowed" header is set before calling the handler.
	GlobalOPTIONS http.Handler

	// Configurable http.Handler which is called when no matching route is
	// found. If it is not set, http.NotFound is used.
	NotFound http.Handler

	// Configurable http.Handler which is called when a request
	// cannot be routed and HandleMethodNotAllowed is true.
	// If it is not set, http.Error with http.StatusMethodNotAllowed is used.
	// The "Allow" header with allowed request methods is set before the handler
	// is called.
	MethodNotAllowed http.Handler

	// Function to handle panics recovered from http handlers.
	// It should be used to generate a error page and return the http error code
	// 500 (Internal Server Error).
	// The handler can be used to keep your server from crashing because of
	// unrecovered panics.
	PanicHandler func(http.ResponseWriter, *http.Request, interface{})
	// contains filtered or unexported fields
}

Router is a http.Handler which can be used to dispatch requests to different handler functions via configurable routes

func New

func New() *Router

New returns a new initialized Router. Path auto-correction, including trailing slashes, is enabled by default.

func (*Router) DELETE

func (r *Router) DELETE(path string, handle gcore.Handle)

DELETE is a shortcut for router.Handle(http.MethodDelete, path, handle)

func (*Router) GET

func (r *Router) GET(path string, handle gcore.Handle)

GET is a shortcut for router.Handle(http.MethodGet, path, handle)

func (*Router) HEAD

func (r *Router) HEAD(path string, handle gcore.Handle)

HEAD is a shortcut for router.Handle(http.MethodHead, path, handle)

func (*Router) Handle

func (r *Router) Handle(method, path string, handle gcore.Handle)

Handle registers a new request handle with the given path and method.

For GET, POST, PUT, PATCH and DELETE requests the respective shortcut functions can be used.

This function is intended for bulk loading and to allow the usage of less frequently used, non-standardized or custom methods (e.g. for internal communication with a proxy).

func (*Router) Handler

func (r *Router) Handler(method, path string, handler http.Handler)

Handler is an adapter which allows the usage of an http.Handler as a request handle. The Params are available in the request context under ParamsKey.

func (*Router) HandlerFunc

func (r *Router) HandlerFunc(method, path string, handler http.HandlerFunc)

HandlerFunc is an adapter which allows the usage of an http.HandlerFunc as a request handle.

func (*Router) Lookup

func (r *Router) Lookup(method, path string) (gcore.Handle, gcore.Params, bool)

Lookup allows the manual lookup of a method + path combo. This is e.g. useful to build a framework around this router. If the path was found, it returns the handle function and the path parameter values. Otherwise the third return value indicates whether a redirection to the same path with an extra / without the trailing slash should be performed.

func (*Router) OPTIONS

func (r *Router) OPTIONS(path string, handle gcore.Handle)

OPTIONS is a shortcut for router.Handle(http.MethodOptions, path, handle)

func (*Router) PATCH

func (r *Router) PATCH(path string, handle gcore.Handle)

PATCH is a shortcut for router.Handle(http.MethodPatch, path, handle)

func (*Router) POST

func (r *Router) POST(path string, handle gcore.Handle)

POST is a shortcut for router.Handle(http.MethodPost, path, handle)

func (*Router) PUT

func (r *Router) PUT(path string, handle gcore.Handle)

PUT is a shortcut for router.Handle(http.MethodPut, path, handle)

func (*Router) ServeFiles

func (r *Router) ServeFiles(path string, root http.FileSystem)

ServeFiles serves files from the given file system root. The path must end with "/*filepath", files are then served from the local path /defined/root/dir/*filepath. For example if root is "/etc" and *filepath is "passwd", the local file "/etc/passwd" would be served. Internally a http.FileServer is used, therefore http.NotFound is used instead of the Router's NotFound handler. To use the operating system's file system implementation, use http.Dir:

router.ServeFiles("/src/*filepath", http.Dir("/var/www"))

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP makes the router implement the http.Handler interface.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL