r2

package module
v0.3.3 Latest Latest
Warning

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

Go to latest
Published: Aug 3, 2022 License: MIT Imports: 6 Imported by: 0

README

R2

GitHub Actions codecov Go Report Card PkgGoDev

A minimalist HTTP request routing helper for Go.

The name "R2" stands for "Request Routing". That's all, R2 is just a capable little helper for HTTP request routing, not another fancy web framework that wraps net/http.

R2 is built for people who:

  • Think net/http is powerful enough and easy to use.
  • Don't want to use any web framework that wraps net/http.
  • Don't want to use any variant of http.Handler.
  • Want http.ServeMux to have better performance and support path parameters.

Features

  • Extremely easy to use
  • Blazing fast (see benchmarks)
  • Based on radix tree
  • Sub-router support
  • Path parameter support
  • No http.Handler variant
  • Middleware support
  • Zero third-party dependencies
  • 100% code coverage

Installation

Open your terminal and execute

$ go get github.com/aofei/r2

done.

The only requirement is the Go, at least v1.13.

Hello, 世界

Create a file named hello.go

package main

import (
	"fmt"
	"net/http"

	"github.com/aofei/r2"
)

func main() {
	r := &r2.Router{}
	r.Handle("", "/hello/:name", http.HandlerFunc(hello))
	http.ListenAndServe("localhost:8080", r)
}

func hello(rw http.ResponseWriter, req *http.Request) {
	fmt.Fprintf(rw, "Hello, %s\n", r2.PathParam(req, "name"))
}

and run it

$ go run hello.go

then visit http://localhost:8080/hello/世界.

Community

If you want to discuss R2, or ask questions about it, simply post questions or ideas here.

Contributing

If you want to help build R2, simply follow this to send pull requests here.

License

This project is licensed under the MIT License.

License can be found here.

Documentation

Overview

Package r2 implements a minimalist HTTP request routing helper for Go.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Context added in v0.3.0

func Context() context.Context

Context returns a non-nil context.Context that is never canceled and has no deadline. It is typically used in the http.Server.BaseContext to avoid the Router.Handler from calling the http.Request.WithContext, which can significantly improve routing performance.

func PathParam added in v0.2.0

func PathParam(req *http.Request, name string) string

PathParam returns a path parameter value of the req for the name. It returns empty string if not found.

func PathParamNames added in v0.2.0

func PathParamNames(req *http.Request) []string

PathParamNames returns path parameter names of the req. It returns nil if not found.

func PathParamValues added in v0.2.0

func PathParamValues(req *http.Request) []string

PathParamValues returns path parameter values of the req. It returns nil if not found.

Types

type Middleware

type Middleware interface {
	// ChainHTTPHandler chains the next to the returned [http.Handler].
	//
	// Typically, the returned [http.Handler] is a closure which does
	// something with the [http.ResponseWriter] and [http.Request] passed to
	// it, and then calls the next.ServeHTTP.
	ChainHTTPHandler(next http.Handler) http.Handler
}

Middleware is used to chain the http.Handler.

type MiddlewareFunc

type MiddlewareFunc func(next http.Handler) http.Handler

MiddlewareFunc is an adapter to allow the use of an ordinary function as a Middleware.

func (MiddlewareFunc) ChainHTTPHandler

func (mf MiddlewareFunc) ChainHTTPHandler(next http.Handler) http.Handler

ChainHTTPHandler implements the Middleware.

type Router

type Router struct {
	// Parent is the parent [Router].
	Parent *Router

	// PathPrefix is the path prefix of all routes to be registered.
	PathPrefix string

	// Middlewares is the [Middleware] chain that performs after routing.
	Middlewares []Middleware

	// NotFoundHandler writes not found responses. It is used when the
	// [Router.Handler] fails to find a matching handler for a request.
	//
	// If the NotFoundHandler is nil, a default one is used.
	//
	// Note that the NotFoundHandler will be ignored when the
	// [Router.Parent] is not nil.
	NotFoundHandler http.Handler

	// MethodNotAllowedHandler writes method not allowed responses. It is
	// used when the [Router.Handler] finds a handler that matches only the
	// path but not the method for a request.
	//
	// If the MethodNotAllowedHandler is nil, a default one is used.
	//
	// Note that the MethodNotAllowedHandler will be ignored when the
	// [Router.Parent] is not nil.
	MethodNotAllowedHandler http.Handler

	// TSRHandler writes TSR (Trailing Slash Redirect) responses. It may be
	// used when the path of a registered route ends with "/*", and the
	// [Router.Handler] fails to find a matching handler for a request whose
	// path has the same prefix but does not end with such pattern. See the
	// [Router.Handle] for more details.
	//
	// If the TSRHandler is nil, a default one is used.
	//
	// Note that the TSRHandler will be ignored when the [Router.Parent] is
	// not nil.
	TSRHandler http.Handler
	// contains filtered or unexported fields
}

Router is a registry of all registered routes for HTTP request routing.

Make sure that all fields of the Router have been finalized before calling any of its methods.

func (*Router) Handle

func (r *Router) Handle(method, path string, h http.Handler, ms ...Middleware)

Handle registers a new route for the method (empty string means catch-all) and path with the matching h and optional ms.

A ':' followed by a name in the path declares a path parameter that matches all characters except '/'. And an '*' in the path declares a wildcard path parameter that greedily matches all characters, with "*" as its name. The PathParam can be used to get those declared path parameters after a request is matched.

When the path ends with "/*", and there is at least one path element before it without any other path parameters, a sepcial catch-all route will be automatically registered with the result of path[:len(path)-2] as its path and the r.TSRHandler as its handler. This special catch-all route will be overridden if a route with such path is explicitly registered, regardless of its method.

func (*Router) Handler

func (r *Router) Handler(req *http.Request) (http.Handler, *http.Request)

Handler returns a matched http.Handler for the req along with a possible revision of the req.

The returned http.Handler is always non-nil.

The revision of the req only happens when the matched route has at least one path parameter and the result of req.Context() has nothing to do with the Context. Otherwise, the req itself is returned.

func (*Router) ServeHTTP

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

ServeHTTP implements the http.Handler.

func (*Router) Sub

func (r *Router) Sub(pathPrefix string, ms ...Middleware) *Router

Sub returns a new instance of the Router inherited from the r with the pathPrefix and optional ms.

Jump to

Keyboard shortcuts

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