gor

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Feb 15, 2023 License: Apache-2.0 Imports: 9 Imported by: 0

README

Go Reference

gor

gor is a lightweight router for creating Go HTTP services. It helps build large REST API services that can be maintained as the project grows.
gor is built on the context package.
See examples

Install

go get -u github.com/pchchv/gor

Features

  • Fast
  • Reliability
  • Lightweight
  • Context control
  • Go.mod support
  • 100% compatible with net/http
  • Designed for modular/composable APIs

Middlewares

gor comes with an optional middleware package that provides a set of standard net/http middleware.
Any middleware in the ecosystem that is also compatible with net/http can be used with gor's mux.

Core middlewares

gor/middleware Handler description
AllowContentEncoding Provides a white list of Content-Encoding headers of the request
AllowContentType Explicit white list of accepted Content-Types requests
BasicAuth Basic HTTP authentication
Compress Gzip compression for clients accepting compressed responses
ContentCharset Providing encoding for Content-Type request headers
CleanPath Clean the double slashes from request path
GetHead Automatically route undefined HEAD requests to GET handlers
Heartbeat Monitoring endpoint to check the pulse of the servers
Logger Logs the start and end of each request with the elapsed processing time
NoCache Sets response headers to prevent caching by clients
Profiler Simple net/http/pprof connection to routers
RealIP Sets RemoteAddr http.Request to X-Real-IP or X-Forwarded-For
Recoverer Gracefully absorbs panic and prints a stack trace
RequestID Injects a request ID in the context of each request
RedirectSlashes Redirect slashes in routing paths
RouteHeaders Handling routes for request headers
SetHeader Middleware to set the key/response header value
StripSlashes Strip slashes in routing paths
Throttle Puts a ceiling on the number of concurrent requests
Timeout Signals to the request context that the timeout deadline has been reached
URLFormat Parse the extension from the url and put it in the request context
WithValue Middleware to set the key/value in the context of a request

context

context is a tiny package available in stdlib since go1.7, providing a simple interface for context signaling via call stacks and goroutines.
Learn more at The Go Blog

Documentation

Index

Constants

This section is empty.

Variables

View Source
var RouteCtxKey = &contextKey{"RouteContext"}

RouteCtxKey is the context.Context key to store the request context.

Functions

func RegisterMethod

func RegisterMethod(method string)

RegisterMethod adds support for custom HTTP method handlers

func URLParam

func URLParam(r *http.Request, key string) string

URLParam returns the url parameter from a http.Request object.

func URLParamFromCtx

func URLParamFromCtx(ctx context.Context, key string) string

URLParamFromCtx returns the url parameter from a http.Request Context.

func Walk

func Walk(r Routes, walkFn WalkFunc) error

Walk walks any router tree that implements Routes interface.

Types

type ChainHandler

type ChainHandler struct {
	Endpoint http.Handler

	Middlewares Middlewares
	// contains filtered or unexported fields
}

ChainHandler is a http.Handler with support for handler composition and execution.

func (*ChainHandler) ServeHTTP

func (c *ChainHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

type Context

type Context struct {
	Routes Routes

	// Routing path/method override used during route lookup.
	RoutePath   string
	RouteMethod string

	// URLParams are the stack of routeParams captured during the routing lifecycle in the sub-routers stack.
	URLParams RouteParams

	// Routing pattern stack throughout the request lifecycle on all connected routers.
	// This is a record of all matching patterns in the sub-routers stack.
	RoutePatterns []string
	// contains filtered or unexported fields
}

Context is the default routing context set on the root node of the request context to track route patterns, URL parameters and optional routing path.

func NewRouteContext

func NewRouteContext() *Context

NewRouteContext returns a new routing Context object.

func RouteContext

func RouteContext(ctx context.Context) *Context

RouteContext returns gor routing Context object from a http.Request Context.

func (*Context) Reset

func (ctx *Context) Reset()

Reset a routing context to its initial state.

func (*Context) RoutePattern

func (ctx *Context) RoutePattern() string

RoutePattern builds a routing pattern string for a particular request at a particular routing point. This means that the value will change throughout the request execution time in the router. Therefore, it is recommended to use this value only after the next handler is called.

func (*Context) URLParam

func (ctx *Context) URLParam(key string) string

URLParam returns the corresponding URL parameter from the request routing context.

type Middlewares

type Middlewares []func(http.Handler) http.Handler

Middlewares is a slice of standard middleware handlers with methods to compose middleware chains and http.Handler's.

func Chain

func Chain(middlewares ...func(http.Handler) http.Handler) Middlewares

Chain returns a Middlewares type from a slice of middleware handlers.

func (Middlewares) Handler

func (mws Middlewares) Handler(h http.Handler) http.Handler

Handler builds and returns a http.Handler from the chain of middlewares, with `h http.Handler` as the final handler.

func (Middlewares) HandlerFunc

func (mws Middlewares) HandlerFunc(h http.HandlerFunc) http.Handler

HandlerFunc builds and returns a http.Handler from the chain of middlewares, with `h http.Handler` as the final handler.

type Mux

type Mux struct {
	// contains filtered or unexported fields
}

Mux is a simple HTTP route multiplexer that parses the request path, writes any URL parameters and executes the end handler. It implements the http.Handler interface and is friendly with the standard library.

func NewMux

func NewMux() *Mux

NewMux returns a newly initialized Mux object that implements the Router interface.

func NewRouter

func NewRouter() *Mux

NewRouter returns a new Mux object that implements the Router interface.

func (*Mux) Connect

func (mx *Mux) Connect(pattern string, handlerFn http.HandlerFunc)

Connect adds a route `pattern` that matches a CONNECT http method to execute the `handlerFn` http.HandlerFunc.

func (*Mux) Delete

func (mx *Mux) Delete(pattern string, handlerFn http.HandlerFunc)

Delete adds a route `pattern` that matches a DELETE http method to execute the `handlerFn` http.HandlerFunc.

func (*Mux) Get

func (mx *Mux) Get(pattern string, handlerFn http.HandlerFunc)

Get adds a route `pattern` that matches a GET http method to execute the `handlerFn` http.HandlerFunc.

func (*Mux) Group

func (mx *Mux) Group(fn func(r Router)) Router

Group creates a new inline-Mux with a fresh middleware stack. This is useful for a group of handlers on the same routing path that use an additional set of middleware.

func (*Mux) Handle

func (mx *Mux) Handle(pattern string, handler http.Handler)

Handle adds a `pattern` route matching any http method to execute `handler` http.Handler.

func (*Mux) HandleFunc

func (mx *Mux) HandleFunc(pattern string, handlerFn http.HandlerFunc)

HandleFunc adds a `pattern` route that matches any http method to. execute `handlerFn` http.HandlerFunc.

func (*Mux) Head

func (mx *Mux) Head(pattern string, handlerFn http.HandlerFunc)

Head adds a route `pattern` that matches a HEAD http method to execute the `handlerFn` http.HandlerFunc.

func (*Mux) Match

func (mx *Mux) Match(rctx *Context, method, path string) bool

Match searches the routing tree for the handler matching the method/path. This is similar to routing an http request, but without executing the handler afterwards. The *Context state is updated at runtime, so manage the state carefully or make a NewRouteContext().

func (*Mux) Method

func (mx *Mux) Method(method, pattern string, handler http.Handler)

Method adds a route `pattern` that matches `method` http method to execute the `handler` http.Handler.

func (*Mux) MethodFunc

func (mx *Mux) MethodFunc(method, pattern string, handlerFn http.HandlerFunc)

MethodFunc adds a route `pattern` that matches `method` http method to execute the `handlerFn` http.HandlerFunc.

func (*Mux) MethodNotAllowed

func (mx *Mux) MethodNotAllowed(handlerFn http.HandlerFunc)

MethodNotAllowed sets a custom http.HandlerFunc to route paths where the method is unresolved. The default handler returns a 405 with an empty body.

func (*Mux) MethodNotAllowedHandler

func (mx *Mux) MethodNotAllowedHandler() http.HandlerFunc

MethodNotAllowedHandler returns the default Mux 405 responder whenever a method cannot be resolved for a route.

func (*Mux) Middlewares

func (mx *Mux) Middlewares() Middlewares

Middlewares returns a slice of middleware handler functions.

func (*Mux) Mount

func (mx *Mux) Mount(pattern string, handler http.Handler)

Mount attaches another http.Handler or gor Router as a subrouter on the routing path. It is very useful to split a large API into many independent routers and merge them into a single service using Mount. Note that Mount() simply sets a wildcard in the `template` that will continue routing in the `handler`, which in most cases is another gor.Router. As a result, if you define two Mount() routes on the same pattern, mount will cause a panic.

func (*Mux) NotFound

func (mx *Mux) NotFound(handlerFn http.HandlerFunc)

NotFound sets a custom http.HandlerFunc to route paths that cannot be found. The default 404 handler is `http.NotFound`.

func (*Mux) NotFoundHandler

func (mx *Mux) NotFoundHandler() http.HandlerFunc

NotFoundHandler returns the default Mux 404 responder whenever a route cannot be found.

func (*Mux) Options

func (mx *Mux) Options(pattern string, handlerFn http.HandlerFunc)

Options adds a route `pattern` that matches a OPTIONS http method to execute the `handlerFn` http.HandlerFunc.

func (*Mux) Patch

func (mx *Mux) Patch(pattern string, handlerFn http.HandlerFunc)

Patch adds a route `pattern` that matches a PATCH http method to execute the `handlerFn` http.HandlerFunc.

func (*Mux) Post

func (mx *Mux) Post(pattern string, handlerFn http.HandlerFunc)

Post adds a route `pattern` that matches a POST http method to execute the `handlerFn` http.HandlerFunc.

func (*Mux) Put

func (mx *Mux) Put(pattern string, handlerFn http.HandlerFunc)

Put adds a route `pattern` that matches a PUT http method to execute the `handlerFn` http.HandlerFunc.

func (*Mux) Route

func (mx *Mux) Route(pattern string, fn func(r Router)) Router

Route creates a new Mux with a fresh middleware stack and mounts it along the `pattern` as a subrouter. This is essentially a shortened Mount call.

func (*Mux) Routes

func (mx *Mux) Routes() []Route

Routes returns a slice of routing information from the tree, useful for traversing available routes of a router.

func (*Mux) ServeHTTP

func (mx *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP is the only method of the http.Handler interface that makes Mux compatible with the standard library. It uses sync.Pool to get and reuse routing contexts for each request.

func (*Mux) Trace

func (mx *Mux) Trace(pattern string, handlerFn http.HandlerFunc)

Trace adds a route `pattern` that matches a TRACE http method to execute the `handlerFn` http.HandlerFunc.

func (*Mux) Use

func (mx *Mux) Use(middlewares ...func(http.Handler) http.Handler)

Use appends a middleware handler to the Mux middleware stack. The middleware stack for any Mux will execute before finding a matching route to a specific handler, which provides opportunity to respond early, change the course of the request execution, or set request-scoped values for the next http.Handler.

func (*Mux) With

func (mx *Mux) With(middlewares ...func(http.Handler) http.Handler) Router

With adds inline middlewares for the endpoint handler.

type Route

type Route struct {
	SubRoutes Routes
	Handlers  map[string]http.Handler // HTTP method
	Pattern   string
}

Route describes the details of a routing handler.

type RouteParams

type RouteParams struct {
	Keys   []string
	Values []string
}

RouteParams is a structure to track URL routing parameters efficiently.

func (*RouteParams) Add

func (s *RouteParams) Add(key, value string)

Add will append a URL parameter to the end of the route param

type Router

type Router interface {
	http.Handler
	Routes

	// Use appends one or more middlewares to the Router stack.
	Use(middlewares ...func(http.Handler) http.Handler)

	// With built-in middleware modules to the endpoint handler.
	With(middlewares ...func(http.Handler) http.Handler) Router

	// Group adds a new inline Router along the current routing path,
	// with a fresh middleware stack for the inline Router.
	Group(fn func(r Router)) Router

	// Route mounts a sub Router on the `pattern` string.
	Route(pattern string, fn func(r Router)) Router

	// Mount attaches another http.Handler along the ./pattern/*
	Mount(pattern string, h http.Handler)

	// Handle adds routes for a `pattern` that matches all HTTP methods.
	Handle(pattern string, h http.Handler)
	// HandleFunc adds routes for a `pattern` that matches all HTTP methods.
	HandleFunc(pattern string, h http.HandlerFunc)

	// Method adds routes for `pattern` which matches the HTTP method `method`.
	Method(method, pattern string, h http.Handler)
	// MethodFunc adds routes for `pattern` which matches the HTTP method `method`.
	MethodFunc(method, pattern string, h http.HandlerFunc)

	// HTTP-method routing along `pattern`
	Get(pattern string, h http.HandlerFunc)
	Put(pattern string, h http.HandlerFunc)
	Post(pattern string, h http.HandlerFunc)
	Head(pattern string, h http.HandlerFunc)
	Patch(pattern string, h http.HandlerFunc)
	Trace(pattern string, h http.HandlerFunc)
	Delete(pattern string, h http.HandlerFunc)
	Connect(pattern string, h http.HandlerFunc)
	Options(pattern string, h http.HandlerFunc)

	// NotFound defines a handler that will respond whenever a route cannot be found.
	NotFound(h http.HandlerFunc)

	// MethodNotAllowed defines a handler that will react whenever the method is not allowed.
	MethodNotAllowed(h http.HandlerFunc)
}

Router consisting of basic routing methods, using only the standard net/http.

type Routes

type Routes interface {
	// Routes returns the routing tree in an easily traversable structure.
	Routes() []Route

	// Middlewares returns the list of middlewares in use by the router.
	Middlewares() Middlewares

	// Match searches the routing tree for a handler that matches the method/path -
	// similar to routing an http request, but without the handler being executed afterwards.
	Match(rctx *Context, method, path string) bool
}

Routes adds two methods for router traversal, which are also used by the `docgen` subpackage to generation documentation for Routers.

type WalkFunc

type WalkFunc func(method string, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error

WalkFunc is the type of the function called for each method and route visited by Walk.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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