httpr

package module
v0.3.2 Latest Latest
Warning

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

Go to latest
Published: Sep 5, 2023 License: MIT Imports: 4 Imported by: 0

README

httpr

It is an implementation of yet another HTTP router.

The reason why this router was made is to be able to have pretty paths with parameters and regular endpoints at the same level. Like this:

GET /:a/:b
GET /assets/*filepath

In routers like httprouter this is not allowed.

This router is used like many others., example:

r := httpr.New()

r.Handler(http.MethodGet, "/", func(w http.ResponseWriter, r *http.Request) {
	...
})

r.ServeStatic("/assets/*filepath", http.FS(os.Dir(".")))

r.NotFoundHandler = func(w http.ResponseWriter, r *http.Request) {
	...
}

s := r.Sub("/api/v1")

s.Handler(http.MethodGet, "/", func(w http.ResponseWriter, r *http.Request) {
	...
})

if err := http.ListenAndServe(":8000", r); err != nil {
	...
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ParamsKey paramsKey = paramsKey{}

ParamsKey is used as a key for Params in a request's Context.

Functions

func Param

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

Param returns a URL parameter set with :key, or an empty string if not found.

Types

type Params

type Params map[string]string

Params holds path parameters that are set as :key.

type Router

type Router struct {
	NotFoundHandler http.HandlerFunc
	// contains filtered or unexported fields
}

func New

func New() *Router

func (*Router) Handler

func (rr *Router) Handler(method, pattern string, handler http.HandlerFunc) error

Handler registers a handler for provided pattern for a given HTTP method. Pattern must start with a slash (/) symbol.

func (*Router) ServeHTTP

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

func (*Router) ServeStatic

func (rr *Router) ServeStatic(path string, root http.FileSystem) error

ServeStatic serves a given file system.

Path should end with /*filepath to work.

func (*Router) Sub added in v0.3.0

func (rr *Router) Sub(base string) *subPath

Sub creates a group of handlers with the same base path.

How to use:

r := httpr.New()
...
s := r.Sub("/api/v1")
s.Handler(http.MethodGet, "/", func(w, r) {...})
s.Handler(http.MethodGet, "/section", func(w, r) {...})

Jump to

Keyboard shortcuts

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