route

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2019 License: MIT Imports: 19 Imported by: 11

README

Build Status codecov GoDoc Go Report Card

Few main features

  • Minimal core.
  • No external runtime dependencies. Custom middlewares which requires 3th party dependecies are places in separates repositories under goroute org.
  • HTTP Routing.
  • Middlewares support.
  • Global error handling.
  • "Correct" handler func signature.

Why goroute

There are a lot of good web frameworks / routers for go already so why created yet another one. Few reasons:

1. Imperfect handler signature

Routers like httprouter, gorilla etc. mux are trying to be compliant with http standard library. This is a good goal but http standard library isn't ideal. Don't get me wrong. Go has one of the best http standard libraries but I found it be too low level for 90% of use cases. Let's look at the example:

Go http standard library has a HandleFunc method which allows to execute handlers based on a path. If you look at function signature it allows to get the request from http.Request and write response using http.ResponseWriter.

http.HandleFunc("/", func (w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusOK)
	fmt.Fprintf(w, "Hello")
})

Since it doesn't force to return error we should terminate execution with explicit return statement. We also need to think how to log error and it's quite hard to have global error handling in one place.

http.HandleFunc("/users", func (w http.ResponseWriter, r *http.Request) {
	users, err := db.GetUsers()
	if err != nil {
		w.WriteHeader(http.StatusInternalError)
		log.Errorf("cannot get users: %v", err)
		return
	}
	
	usersJSON, err := json.Marshal(users)
	if err != nil {
		w.WriteHeader(http.StatusInternalError)
		log.Errorf("cannot marshal users to json: %v", err)
		return
	}
	
	w.WriteHeader(http.StatusOK)
	w.Header().Add("Content-Type", "application/json")
	w.Write(usersJSON)
})

Similar handler signatures like func (w http.ResponseWriter, r *http.Request), func (ctx framework.Context) can be found in 90% of all go web frameworks / routers.

Let's look how can we improve this but changing function signature.

mux := route.NewServeMux()
mux.GET("/users", func (c route.Context) error {
	return c.String(http.StatusOK, "Hello")
})

The same use case with error handling.

mux := route.NewServeMux()
mux.GET("/users", func (c route.Context) error {
	users, err := db.GetUsers()
	if err != nil {
		return fmt.Errorf("cannot get users: %v", err")
	}
	return c.JSON(http.StatusOK, users)
})

By simply forcing to return error we now have much cleaner code which not only make it more clear and less boilerplate but also allows to have much simpler global error handling implementation.

P.S If you look at grpc go it has similar handlers signature which allows returns error.

func (s *server) GetUsers(ctx context.Context, in *pb.GetUsersRequest) (*pb.GetUsersReply, error) {
	users, err := s.db.GetUsers()
	if err != nil {
		return fmt.Errorf("cannot get users: %v", err")
	}
	return &pb.GetUsersReply{Users: users}, nil
}

2. Being minimalist but depending on external libraries

There is one great web framework called echo. I used it for my few first projects and really liked it. But... while echo calls itself minimalist web framework it depends on 3th party libraries like github.com/dgrijalva/jwt-go, github.com/valyala/fasttemplate, golang.org/x/crypto. Lets look why.

  1. github.com/dgrijalva/jwt-go is used for jwt middleware which is placed under middleware/jwt.go. This means that you automatically forced to add this dependency even if you are not using jwt middleware.

  2. github.com/valyala/fasttemplate is used for logging templates which is built into the framework.

  3. golang.org/x/crypto is used for auto HTTPS via Let's Encrypt. What if I'm running my web service in kubernetes or docker swarm and I have cluster level load balancer which terminates HTTPS traffic? If you need https on lowest level you can create it by using golang.org/x/crypto/acme/autocert package in few lines of code.

How can we solve this?

Goroute github.com organization is structured in a way that each custom middleware is placed in it's own repo with it's own 3th party dependencies. Such approach not only allows to have separate versioning but also keeps main goroute route small and minimalist.

3. Seeking "best" performance

You may notice that there is a trend for go web frameworks developers to advertise how their frameworks are faster than others and they are playing hello world benchmark battles. What does it mean to have high performance? In real world services your web api endpoint is probably going to call database which will bottleneck first. If not then simply scale horizontally and you are good to go. If you really have a huge load since you working on ads serving etc. then even standard underlying go http primitives are not going to help and you are probably already switched to some custom http/tcp implementations or already using Rust.

Goroute tries to be minimal and uses standard go http server by implementing ServeHTTP interface. There are some simple optimizations like sync.Pool for having less allocations but nothing that feels hacky or over-engineered.

4. Overengineering

Session control, dependency injection, caching, logging, configuration parsing, automatic HTTPS, performance supervising, context handling, ORM supporting, requests simulating, Webassembly, MVC, sessions, caching, Websocket.

If you need all these features in one place then visit beego or iris and you are well covered. Well.. maybe not. I was surprised when I saw that beego has builtin orm for SQL and popular databases like MySQL, Postgres etc. If you writing boring CRUD you may want to us ORM for sure, but there are event better packages for that like gorm. For one it may sound awesome but it really isn't. What if I'm using NoSQL database like MongoDB or googles DataStore? When I don't need traditional ORM at all.

Getting Started

Prerequisites

You need to have at least go 1.11 installed on you local machine.

Installing

Install go route package with go get

go get -u github.com/goroute/route

Start your first server. Create main.go file and add:

package main

import (
    "net/http"
    "log"
    "github.com/goroute/route"
)

type helloResponse struct {
	Title string `json:"title"`
}

func main() {
	mux := route.NewServeMux()
	
	mux.Use(func(c route.Context, next route.HandlerFunc) error {
	    log.Println("Hello, Middleware!")
	    return next(c)
	})
	
	mux.GET("/", func(c route.Context) error {
	    return c.JSON(http.StatusOK, &helloResponse{Title:"Hello, JSON!"})
	})
	
	log.Fatal(http.ListenAndServe(":9000", mux))
}

Run it

go run main.go

More examples

See examples

Built With

Contributing

Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests to us.

Versioning

We use SemVer for versioning. For the versions available, see the tags on this repository.

License

This project is licensed under the MIT License - see the LICENSE.md file for details

Acknowledgments

  • This project is largely inspired by echo. Parts of the code are adopted from echo. See NOTICE.

Documentation

Overview

Package route implements HTTP request miltiplexer.

Index

Constants

View Source
const (
	MIMEApplicationJSON                  = "application/json"
	MIMEApplicationJSONCharsetUTF8       = MIMEApplicationJSON + "; " + charsetUTF8
	MIMEApplicationJavaScript            = "application/javascript"
	MIMEApplicationJavaScriptCharsetUTF8 = MIMEApplicationJavaScript + "; " + charsetUTF8
	MIMEApplicationXML                   = "application/xml"
	MIMEApplicationXMLCharsetUTF8        = MIMEApplicationXML + "; " + charsetUTF8
	MIMETextXML                          = "text/xml"
	MIMETextXMLCharsetUTF8               = MIMETextXML + "; " + charsetUTF8
	MIMEApplicationForm                  = "application/x-www-form-urlencoded"
	MIMEApplicationProtobuf              = "application/protobuf"
	MIMEApplicationMsgpack               = "application/msgpack"
	MIMETextHTML                         = "text/html"
	MIMETextHTMLCharsetUTF8              = MIMETextHTML + "; " + charsetUTF8
	MIMETextPlain                        = "text/plain"
	MIMETextPlainCharsetUTF8             = MIMETextPlain + "; " + charsetUTF8
	MIMEMultipartForm                    = "multipart/form-data"
	MIMEOctetStream                      = "application/octet-stream"
)

MIME types

View Source
const (
	HeaderAccept              = "Accept"
	HeaderAcceptEncoding      = "Accept-Encoding"
	HeaderAllow               = "Allow"
	HeaderAuthorization       = "Authorization"
	HeaderContentDisposition  = "Content-Disposition"
	HeaderContentEncoding     = "Content-Encoding"
	HeaderContentLength       = "Content-Length"
	HeaderContentType         = "Content-Type"
	HeaderCookie              = "Cookie"
	HeaderSetCookie           = "Set-Cookie"
	HeaderIfModifiedSince     = "If-Modified-Since"
	HeaderLastModified        = "Last-Modified"
	HeaderLocation            = "Location"
	HeaderUpgrade             = "Upgrade"
	HeaderVary                = "Vary"
	HeaderWWWAuthenticate     = "WWW-Authenticate"
	HeaderXForwardedFor       = "X-Forwarded-For"
	HeaderXForwardedProto     = "X-Forwarded-Proto"
	HeaderXForwardedProtocol  = "X-Forwarded-Protocol"
	HeaderXForwardedSsl       = "X-Forwarded-Ssl"
	HeaderXUrlScheme          = "X-Url-Scheme"
	HeaderXHTTPMethodOverride = "X-HTTP-Method-Override"
	HeaderXRealIP             = "X-Real-IP"
	HeaderXRequestID          = "X-Request-ID"
	HeaderXRequestedWith      = "X-Requested-With"
	HeaderServer              = "Server"
	HeaderOrigin              = "Origin"

	// Access control
	HeaderAccessControlRequestMethod    = "Access-Control-Request-Method"
	HeaderAccessControlRequestHeaders   = "Access-Control-Request-Headers"
	HeaderAccessControlAllowOrigin      = "Access-Control-Allow-Origin"
	HeaderAccessControlAllowMethods     = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowHeaders     = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials"
	HeaderAccessControlExposeHeaders    = "Access-Control-Expose-Headers"
	HeaderAccessControlMaxAge           = "Access-Control-Max-Age"

	// Security
	HeaderStrictTransportSecurity = "Strict-Transport-Security"
	HeaderXContentTypeOptions     = "X-Content-Type-Options"
	HeaderXXSSProtection          = "X-XSS-Protection"
	HeaderXFrameOptions           = "X-Frame-Options"
	HeaderContentSecurityPolicy   = "Content-Security-Policy"
	HeaderXCSRFToken              = "X-CSRF-Token"
)

Headers

View Source
const (

	// PROPFIND HTTP Header
	PROPFIND = "PROPFIND"
)
View Source
const Version = "1.0.2"

Version is route version.

Variables

View Source
var (
	ErrUnsupportedMediaType        = NewHTTPError(http.StatusUnsupportedMediaType)
	ErrNotFound                    = NewHTTPError(http.StatusNotFound)
	ErrUnauthorized                = NewHTTPError(http.StatusUnauthorized)
	ErrForbidden                   = NewHTTPError(http.StatusForbidden)
	ErrMethodNotAllowed            = NewHTTPError(http.StatusMethodNotAllowed)
	ErrStatusRequestEntityTooLarge = NewHTTPError(http.StatusRequestEntityTooLarge)
	ErrTooManyRequests             = NewHTTPError(http.StatusTooManyRequests)
	ErrBadRequest                  = NewHTTPError(http.StatusBadRequest)
	ErrBadGateway                  = NewHTTPError(http.StatusBadGateway)
	ErrInternalServerError         = NewHTTPError(http.StatusInternalServerError)
	ErrRequestTimeout              = NewHTTPError(http.StatusRequestTimeout)
	ErrServiceUnavailable          = NewHTTPError(http.StatusServiceUnavailable)
	ErrValidatorNotRegistered      = errors.New("validator not registered")
	ErrRendererNotRegistered       = errors.New("Renderer not registered")
	ErrInvalidRedirectCode         = errors.New("invalid redirect status code")
	ErrCookieNotFound              = errors.New("cookie not found")
)

Errors

View Source
var (
	NotFoundHandler = func(c Context) error {
		return ErrNotFound
	}

	MethodNotAllowedHandler = func(c Context) error {
		return ErrMethodNotAllowed
	}
)

Error handlers

Functions

func DefaultSkipper

func DefaultSkipper(Context) bool

DefaultSkipper returns false which processes the middleware.

func NewDefaultTemplateRenderer

func NewDefaultTemplateRenderer(pattern string) *templateRenderer

NewDefaultTemplateRenderer creates default template Renderer with given pattern.

Types

type BindUnmarshaler

type BindUnmarshaler interface {
	// UnmarshalParam decodes and assigns a value from an form or query param.
	UnmarshalParam(param string) error
}

BindUnmarshaler is the interface used to wrap the UnmarshalParam method.

type Binder

type Binder interface {
	Bind(i interface{}, c Context) error
}

Binder is the interface that wraps the Bind method.

type Context

type Context interface {
	// Request returns `*http.Request`.
	Request() *http.Request

	// SetRequest sets `*http.Request`.
	SetRequest(r *http.Request)

	// Response returns `*Response`.
	Response() *Response

	// Path returns the registered path for the handler.
	Path() string

	// SetPath sets the registered path for the handler.
	SetPath(p string)

	// Param returns path parameter by name.
	Param(name string) string

	// ParamNames returns path parameter names.
	ParamNames() []string

	// SetParamNames sets path parameter names.
	SetParamNames(names ...string)

	// ParamValues returns path parameter values.
	ParamValues() []string

	// SetParamValues sets path parameter values.
	SetParamValues(values ...string)

	// QueryParam returns the query param for the provided name.
	QueryParam(name string) string

	// QueryParams returns the query parameters as `url.Values`.
	QueryParams() url.Values

	// QueryString returns the URL query string.
	QueryString() string

	// FormValue returns the form field value for the provided name.
	FormValue(name string) string

	// FormParams returns the form parameters as `url.Values`.
	FormParams() (url.Values, error)

	// FormFile returns the multipart form file for the provided name.
	FormFile(name string) (*multipart.FileHeader, error)

	// MultipartForm returns the multipart form.
	MultipartForm() (*multipart.Form, error)

	// Cookie returns the named cookie provided in the request.
	Cookie(name string) (*http.Cookie, error)

	// SetCookie adds a `Set-Cookie` header in HTTP response.
	SetCookie(cookie *http.Cookie)

	// Cookies returns the HTTP cookies sent with the request.
	Cookies() []*http.Cookie

	// Get retrieves data from the context.
	Get(key string) interface{}

	// Set saves data in the context.
	Set(key string, val interface{})

	// Bind binds the request body into provided type `i`. The default Binder
	// does it based on Content-Type header.
	Bind(i interface{}) error

	// Render renders a template with data and sends a text/html response with status
	// code. Renderer must be registered using `mux.Renderer`.
	Render(code int, name string, data interface{}) error

	// HTML sends an HTTP response with status code.
	HTML(code int, html string) error

	// HTMLBlob sends an HTTP blob response with status code.
	HTMLBlob(code int, b []byte) error

	// String sends a string response with status code.
	String(code int, s string) error

	// JSON sends a JSON response with status code.
	JSON(code int, i interface{}) error

	// Blob sends a blob response with status code and content type.
	Blob(code int, contentType string, b []byte) error

	// Stream sends a streaming response with status code and content type.
	Stream(code int, contentType string, r io.Reader) error

	// File sends a response with the content of the file.
	File(file string) error

	// Attachment sends a response as attachment, prompting client to save the
	// file.
	Attachment(file string, name string) error

	// Inline sends a response as inline, opening the file in the browser.
	Inline(file string, name string) error

	// NoContent sends a response with no body and a status code.
	NoContent(code int) error

	// Redirect redirects the request to a provided URL with status code.
	Redirect(code int, url string) error

	// Error invokes the registered HTTP error handler. Generally used by middleware.
	Error(err error)

	// Handler returns the matched handler by router.
	Handler() HandlerFunc

	// SetHandler sets the matched handler by router.
	SetHandler(h HandlerFunc)
}

Context represents the context of the current HTTP request. It holds request and response objects, path, path parameters, data and registered handler.

type DefaultBinder

type DefaultBinder struct{}

DefaultBinder is the default implementation of the Binder interface.

func (*DefaultBinder) Bind

func (b *DefaultBinder) Bind(i interface{}, c Context) (err error)

Bind implements the `Binder#Bind` function.

type Group

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

Group is a set of sub-routes for a specified route. It can be used for inner routes that share a common middleware or functionality that should be separate from the parent mux instance while still inheriting from it.

func (*Group) Add

func (g *Group) Add(method, path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route

Add implements `Mux#Add()` for sub-routes within the Group.

func (*Group) Any

func (g *Group) Any(path string, handler HandlerFunc, middleware ...MiddlewareFunc) []*Route

Any implements `Mux#Any()` for sub-routes within the Group.

func (*Group) CONNECT

func (g *Group) CONNECT(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

CONNECT implements `Mux#CONNECT()` for sub-routes within the Group.

func (*Group) DELETE

func (g *Group) DELETE(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

DELETE implements `Mux#DELETE()` for sub-routes within the Group.

func (*Group) File

func (g *Group) File(path, file string)

File implements `Mux#File()` for sub-routes within the Group.

func (*Group) GET

func (g *Group) GET(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

GET implements `Mux#GET()` for sub-routes within the Group.

func (*Group) Group

func (g *Group) Group(prefix string, middleware ...MiddlewareFunc) *Group

Group creates a new sub-group with prefix and optional sub-group-level middleware.

func (*Group) HEAD

func (g *Group) HEAD(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

HEAD implements `Mux#HEAD()` for sub-routes within the Group.

func (*Group) Match

func (g *Group) Match(methods []string, path string, handler HandlerFunc, middleware ...MiddlewareFunc) []*Route

Match implements `Mux#Match()` for sub-routes within the Group.

func (*Group) OPTIONS

func (g *Group) OPTIONS(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

OPTIONS implements `Mux#OPTIONS()` for sub-routes within the Group.

func (*Group) PATCH

func (g *Group) PATCH(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

PATCH implements `Mux#PATCH()` for sub-routes within the Group.

func (*Group) POST

func (g *Group) POST(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

POST implements `Mux#POST()` for sub-routes within the Group.

func (*Group) PUT

func (g *Group) PUT(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

PUT implements `Mux#PUT()` for sub-routes within the Group.

func (*Group) Static

func (g *Group) Static(prefix, root string)

Static implements `Mux#Static()` for sub-routes within the Group.

func (*Group) TRACE

func (g *Group) TRACE(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

TRACE implements `Mux#TRACE()` for sub-routes within the Group.

func (*Group) Use

func (g *Group) Use(middleware ...MiddlewareFunc)

Use implements `Mux#Use()` for sub-routes within the Group.

type HTTPError

type HTTPError struct {
	Code     int
	Message  interface{}
	Internal error // Stores the error returned by an external dependency
}

HTTPError represents an error that occurred while handling a request.

func NewHTTPError

func NewHTTPError(code int, message ...interface{}) *HTTPError

NewHTTPError creates a new HTTPError instance.

func (*HTTPError) Error

func (he *HTTPError) Error() string

Error makes it compatible with `error` interface.

func (*HTTPError) SetInternal

func (he *HTTPError) SetInternal(err error) *HTTPError

SetInternal sets internal error on HTTPError

type HTTPErrorHandler

type HTTPErrorHandler func(error, Context)

HTTPErrorHandler is a centralized HTTP error handler.

type HandlerFunc

type HandlerFunc func(Context) error

HandlerFunc defines a function to serve HTTP requests.

func WrapHandler

func WrapHandler(h http.Handler) HandlerFunc

WrapHandler wraps `http.Handler` into `mux.HandlerFunc`.

type MiddlewareFunc

type MiddlewareFunc func(c Context, next HandlerFunc) error

MiddlewareFunc defines a function to process middleware.

func WrapMiddleware

func WrapMiddleware(m func(http.Handler) http.Handler) MiddlewareFunc

WrapMiddleware wraps `func(http.Handler) http.Handler` into `mux.MiddlewareFunc`

type Mux

type Mux struct {
	Debug            bool
	HTTPErrorHandler HTTPErrorHandler
	Binder           Binder
	Renderer         Renderer
	// contains filtered or unexported fields
}

Mux is the top-level framework instance.

func NewServeMux

func NewServeMux(opt ...Option) (e *Mux)

NewServeMux creates an instance of mux.

func (*Mux) Add

func (mux *Mux) Add(method, path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route

Add registers a new route for an HTTP method and path with matching handler in the router with optional route-level middleware.

func (*Mux) Any

func (mux *Mux) Any(path string, handler HandlerFunc, middleware ...MiddlewareFunc) []*Route

Any registers a new route for all HTTP methods and path with matching handler in the router with optional route-level middleware.

func (*Mux) CONNECT

func (mux *Mux) CONNECT(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

CONNECT registers a new CONNECT route for a path with matching handler in the router with optional route-level middleware.

func (*Mux) DELETE

func (mux *Mux) DELETE(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

DELETE registers a new DELETE route for a path with matching handler in the router with optional route-level middleware.

func (*Mux) File

func (mux *Mux) File(path, file string, m ...MiddlewareFunc) *Route

File registers a new route with path to serve a static file with optional route-level middleware.

func (*Mux) GET

func (mux *Mux) GET(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

GET registers a new GET route for a path with matching handler in the router with optional route-level middleware.

func (*Mux) Group

func (mux *Mux) Group(prefix string, m ...MiddlewareFunc) (g *Group)

Group creates a new router group with prefix and optional group-level middleware.

func (*Mux) HEAD

func (mux *Mux) HEAD(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

HEAD registers a new HEAD route for a path with matching handler in the router with optional route-level middleware.

func (*Mux) Match

func (mux *Mux) Match(methods []string, path string, handler HandlerFunc, middleware ...MiddlewareFunc) []*Route

Match registers a new route for multiple HTTP methods and path with matching handler in the router with optional route-level middleware.

func (*Mux) NewContext

func (mux *Mux) NewContext(r *http.Request, w http.ResponseWriter) Context

NewContext returns a Context instance.

func (*Mux) OPTIONS

func (mux *Mux) OPTIONS(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

OPTIONS registers a new OPTIONS route for a path with matching handler in the router with optional route-level middleware.

func (*Mux) PATCH

func (mux *Mux) PATCH(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

PATCH registers a new PATCH route for a path with matching handler in the router with optional route-level middleware.

func (*Mux) POST

func (mux *Mux) POST(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

POST registers a new POST route for a path with matching handler in the router with optional route-level middleware.

func (*Mux) PUT

func (mux *Mux) PUT(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

PUT registers a new PUT route for a path with matching handler in the router with optional route-level middleware.

func (*Mux) Pre

func (mux *Mux) Pre(middleware ...MiddlewareFunc)

Pre adds middleware to the chain which is run before router.

func (*Mux) Routes

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

Routes returns the registered routes.

func (*Mux) ServeHTTP

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

ServeHTTP implements `http.Handler` interface, which serves HTTP requests.

func (*Mux) Static

func (mux *Mux) Static(prefix, root string) *Route

Static registers a new route with path prefix to serve static files from the provided root directory.

func (*Mux) TRACE

func (mux *Mux) TRACE(path string, h HandlerFunc, m ...MiddlewareFunc) *Route

TRACE registers a new TRACE route for a path with matching handler in the router with optional route-level middleware.

func (*Mux) Use

func (mux *Mux) Use(middleware ...MiddlewareFunc)

Use adds middleware to the chain which is run after router.

type Option

type Option func(*options)

A Option sets options such as credentials, tls, etc.

func WithBinder

func WithBinder(binder Binder) Option

WithBinder allows to override default mux Binder.

func WithHTTPErrorHandler

func WithHTTPErrorHandler(handler HTTPErrorHandler) Option

WithHTTPErrorHandler allows to override default mux global error handler.

func WithRenderer

func WithRenderer(renderer Renderer) Option

WithRenderer allows to register mux view Renderer.

type Renderer

type Renderer interface {
	Render(io.Writer, string, interface{}, Context) error
}

Renderer is the interface that wraps the Render function.

type Response

type Response struct {
	Writer    http.ResponseWriter
	Status    int
	Size      int64
	Committed bool
	// contains filtered or unexported fields
}

Response wraps an http.ResponseWriter and implements its interface to be used by an HTTP handler to construct an HTTP response. See: https://golang.org/pkg/net/http/#ResponseWriter

func NewResponse

func NewResponse(w http.ResponseWriter) (r *Response)

NewResponse creates a new instance of Response.

func (*Response) After

func (r *Response) After(fn func())

After registers a function which is called just after the response is written. If the `Content-Length` is unknown, none of the after function is executed.

func (*Response) Before

func (r *Response) Before(fn func())

Before registers a function which is called just before the response is written.

func (*Response) CloseNotify

func (r *Response) CloseNotify() <-chan bool

CloseNotify implements the http.CloseNotifier interface to allow detecting when the underlying connection has gone away. This mechanism can be used to cancel long operations on the server if the client has disconnected before the response is ready. See http.CloseNotifier(https://golang.org/pkg/net/http/#CloseNotifier)

func (*Response) Flush

func (r *Response) Flush()

Flush implements the http.Flusher interface to allow an HTTP handler to flush buffered data to the client. See http.Flusher(https://golang.org/pkg/net/http/#Flusher)

func (*Response) Header

func (r *Response) Header() http.Header

Header returns the header map for the writer that will be sent by WriteHeader. Changing the header after a call to WriteHeader (or Write) has no effect unless the modified headers were declared as trailers by setting the "Trailer" header before the call to WriteHeader (see example) To suppress implicit response headers, set their value to nil. Example: https://golang.org/pkg/net/http/#example_ResponseWriter_trailers

func (*Response) Hijack

func (r *Response) Hijack() (net.Conn, *bufio.ReadWriter, error)

Hijack implements the http.Hijacker interface to allow an HTTP handler to take over the connection. See http.Hijacker(https://golang.org/pkg/net/http/#Hijacker)

func (*Response) Write

func (r *Response) Write(b []byte) (n int, err error)

Write writes the data to the connection as part of an HTTP reply.

func (*Response) WriteHeader

func (r *Response) WriteHeader(code int)

WriteHeader sends an HTTP response header with status code. If WriteHeader is not called explicitly, the first call to Write will trigger an implicit WriteHeader(http.StatusOK). Thus explicit calls to WriteHeader are mainly used to send error codes.

type Route

type Route struct {
	Method string `json:"method"`
	Path   string `json:"path"`
	Name   string `json:"name"`
}

Route contains a handler and information for matching against requests.

type Skipper

type Skipper func(Context) bool

Skipper defines a function to skip middleware. Returning true skips processing the middleware.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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