httprouter

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2021 License: MIT Imports: 10 Imported by: 3

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultErrorHandler

func DefaultErrorHandler(w http.ResponseWriter, req *http.Request, verbose bool, err Error)

func DefaultPanicHandler

func DefaultPanicHandler(w http.ResponseWriter, req *http.Request, verbose bool, pv interface{})

func GetParams added in v1.1.0

func GetParams(ctx context.Context) map[string]string

func GetRoute added in v1.1.0

func GetRoute(ctx context.Context) string

func IsStatus

func IsStatus(err error, status int) bool

func JSONRequest

func JSONRequest(req *http.Request, dst interface{}) error

JSONRequest expects application/json content-type and attempts to unmarshal request body into dst. 415 Unsupported Media Type is returned if invalid content-type was provided 400 Bad Request is returned if request body failed to unmarshal

func JSONResponse

func JSONResponse(w http.ResponseWriter, status int, src interface{}) error

JSONResponse sets content-type to application/json and marshals src as json to response body 500 Internal Server Error is returned if src could not be marshaled

func NoopHandler added in v1.1.0

func NoopHandler(http.ResponseWriter, *http.Request) error

func WithRouteData added in v1.1.0

func WithRouteData(ctx context.Context, data RouteData) context.Context

Types

type Error

type Error struct {
	Status      int
	Message     string
	Operational bool
	Cause       error
}

func AsError

func AsError(err error) Error

func NewError

func NewError(status int, opts ...ErrorOpt) Error

func (Error) Error

func (e Error) Error() string

func (Error) Unwrap

func (e Error) Unwrap() error

type ErrorHandler

type ErrorHandler func(w http.ResponseWriter, req *http.Request, verbose bool, err Error)

type ErrorOpt

type ErrorOpt func(*Error)

func Cause

func Cause(cause error) ErrorOpt

func Message

func Message(message string) ErrorOpt

func Messagef

func Messagef(format string, a ...interface{}) ErrorOpt

func Operational

func Operational() ErrorOpt

type ErrorResponse

type ErrorResponse struct {
	Message string `json:"message"`
	Debug   string `json:"debug,omitempty"`
}

type HandlerFunc

type HandlerFunc func(w http.ResponseWriter, req *http.Request) error

type LogRoundtrip

type LogRoundtrip func(rw ResponseWriter, req *http.Request)

type LookupResult added in v1.1.0

type LookupResult struct {
	RouteData
	// StatusCode informs the caller about the result of the lookup.
	// This will generally be `http.StatusNotFound` or `http.StatusMethodNotAllowed` for an
	// error case. On a normal success, the statusCode will be `http.StatusOK`. A redirect code
	// will also be used in the case
	Status  int
	Handler HandlerFunc
	Methods []string // Only has a value when StatusCode is MethodNotAllowed.
}

LookupResult contains information about a route lookup, which is returned from Lookup and can be passed to ServeLookupResult if the request should be served.

type Middleware

type Middleware func(handler HandlerFunc) HandlerFunc

type Opt

type Opt func(c *config)

func WithErrorHandler

func WithErrorHandler(handler ErrorHandler) Opt

func WithHandleOptions

func WithHandleOptions(handleOptions bool) Opt

func WithLogRoundtrip

func WithLogRoundtrip(logRoundtrip LogRoundtrip) Opt

func WithMiddleware

func WithMiddleware(middleware ...Middleware) Opt

func WithOptionsHandler added in v1.1.0

func WithOptionsHandler(handler HandlerFunc) Opt

func WithPanicHandler

func WithPanicHandler(handler PanicHandler) Opt

func WithRedirectTrailingSlash added in v1.1.0

func WithRedirectTrailingSlash(redirectTrailingSlash bool) Opt

func WithVerbose

func WithVerbose(verbose bool) Opt

type PanicHandler

type PanicHandler func(rw http.ResponseWriter, req *http.Request, verbose bool, pv interface{})

type ResponseWriter

type ResponseWriter interface {
	http.ResponseWriter
	http.Pusher

	StatusCode() int
	Size() int
	Latency() time.Duration
}

func NewResponseWriter

func NewResponseWriter(delegate http.ResponseWriter) ResponseWriter

type RouteData added in v1.1.0

type RouteData struct {
	Route  string
	Params map[string]string
}

func GetRouteData added in v1.1.0

func GetRouteData(ctx context.Context) RouteData

type Router

type Router struct {
	// contains filtered or unexported fields
}
Example
package main

import (
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"net/http/httptest"

	"github.com/goes-funky/httprouter"
)

type response struct {
	Message string `json:"message"`
}

func main() {
	router := httprouter.New()
	router.Handler(http.MethodGet, "/greet/:name", func(w http.ResponseWriter, req *http.Request) error {
		params := httprouter.GetParams(req.Context())

		response := response{Message: fmt.Sprintf("Hello %s!", params["name"])}
		return httprouter.JSONResponse(w, http.StatusOK, response)
	})

	server := httptest.NewServer(router)

	client := server.Client()

	httpResp, err := client.Get(server.URL + "/greet/fry")
	if err != nil {
		log.Fatal("failed to GET /greet/fry", err)
	}

	body, err := io.ReadAll(httpResp.Body)
	if err != nil {
		log.Fatal("failed to read http response body", err)
	}

	var resp response
	if err := json.Unmarshal(body, &resp); err != nil {
		log.Fatal("failed to unmarshal http response body", err)
	}

	if resp.Message != "Hello fry!" {
		log.Fatal("unexpected response")
	}
}
Output:

func New

func New(opts ...Opt) *Router

func (*Router) DumpTree added in v1.1.0

func (r *Router) DumpTree() string

func (*Router) HTTPHandler added in v1.1.0

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

HTTPHandler register http.Handler at given method and path

func (*Router) Handler

func (r *Router) Handler(method, path string, handler HandlerFunc, middleware ...Middleware)

Handler registers HandlerFunc at given method and path

func (*Router) Lookup added in v1.1.0

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

func (*Router) ServeHTTP

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

ServeHTTP implements http.Handler

func (*Router) ServeLookupResult added in v1.1.0

func (r *Router) ServeLookupResult(rw http.ResponseWriter, req *http.Request, lr LookupResult)

Directories

Path Synopsis
middleware
zapdriver module

Jump to

Keyboard shortcuts

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