web

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2023 License: Apache-2.0 Imports: 18 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrMethodMismatch is returned when the method in the request does not match
	// the method defined against the route.
	ErrMethodMismatch = mux.ErrMethodMismatch
	// ErrNotFound is returned when no route match is found.
	ErrNotFound = mux.ErrNotFound
	// SkipRouter is used as a return value from WalkFuncs to indicate that the
	// router that walk is about to descend down to should be skipped.
	SkipRouter = mux.SkipRouter
)

Functions

func Bind

func Bind(fn interface{}, render Renderer) http.HandlerFunc

Bind convert fn to HandlerFunc.

func(ctx context.Context)

func(ctx context.Context) R

func(ctx context.Context) error

func(ctx context.Context, req T) R

func(ctx context.Context, req T) error

func(ctx context.Context, req T) (R, error)

func(writer http.ResponseWriter, request *http.Request)

func Vars

func Vars(r *http.Request) map[string]string

Vars returns the route variables for the current request, if any.

func WithContext

func WithContext(parent context.Context, ctx *Context) context.Context

Types

type BuildVarsFunc

type BuildVarsFunc = mux.BuildVarsFunc

BuildVarsFunc is the function signature used by custom build variable functions (which can modify route variables before a route's URL is built).

type Context

type Context struct {
	// A ResponseWriter interface is used by an HTTP handler to
	// construct an HTTP response.
	Writer http.ResponseWriter

	// A Request represents an HTTP request received by a server
	// or to be sent by a client.
	Request *http.Request
	// contains filtered or unexported fields
}

func FromContext

func FromContext(ctx context.Context) *Context

func (*Context) Bind

func (c *Context) Bind(r interface{}) error

Bind checks the Method and Content-Type to select a binding engine automatically, Depending on the "Content-Type" header different bindings are used, for example:

"application/json" --> JSON binding
"application/xml"  --> XML binding

func (*Context) ClientIP

func (c *Context) ClientIP() string

ClientIP implements one best effort algorithm to return the real client IP. It calls c.RemoteIP() under the hood, to check if the remote IP is a trusted proxy or not. If it is it will then try to parse the headers defined in RemoteIPHeaders (defaulting to [X-Forwarded-For, X-Real-Ip]). If the headers are not syntactically valid OR the remote IP does not correspond to a trusted proxy, the remote IP (coming from Request.RemoteAddr) is returned.

func (*Context) ContentType

func (c *Context) ContentType() string

ContentType returns the request header `Content-Type`.

func (*Context) Context

func (c *Context) Context() context.Context

Context returns the request's context.

func (*Context) Cookie

func (c *Context) Cookie(name string) (string, bool)

Cookie returns the named cookie provided in the request.

func (*Context) Data

func (c *Context) Data(code int, contentType string, data []byte) error

Data writes some data into the body stream and updates the HTTP code.

func (*Context) File

func (c *Context) File(filepath string)

File writes the specified file into the body stream in an efficient way.

func (*Context) FileAttachment

func (c *Context) FileAttachment(filepath, filename string)

FileAttachment writes the specified file into the body stream in an efficient way On the client side, the file will typically be downloaded with the given filename

func (*Context) FormParams

func (c *Context) FormParams() (url.Values, error)

FormParams returns the form in the request.

func (*Context) Header

func (c *Context) Header(key string) (string, bool)

Header returns the named header in the request.

func (*Context) IndentedJSON

func (c *Context) IndentedJSON(code int, obj interface{}) error

IndentedJSON serializes the given struct as pretty JSON (indented + endlines) into the response body. It also sets the Content-Type as "application/json".

func (*Context) IndentedXML

func (c *Context) IndentedXML(code int, obj interface{}) error

IndentedXML serializes the given struct as pretty XML (indented + endlines) into the response body. It also sets the Content-Type as "application/xml".

func (*Context) IsWebsocket

func (c *Context) IsWebsocket() bool

IsWebsocket returns true if the request headers indicate that a websocket handshake is being initiated by the client.

func (*Context) JSON

func (c *Context) JSON(code int, obj interface{}) error

JSON serializes the given struct as JSON into the response body. It also sets the Content-Type as "application/json".

func (*Context) MultipartParams

func (c *Context) MultipartParams(maxMemory int64) (*multipart.Form, error)

MultipartParams returns a request body as multipart/form-data. The whole request body is parsed and up to a total of maxMemory bytes of its file parts are stored in memory, with the remainder stored on disk in temporary files.

func (*Context) PathParam

func (c *Context) PathParam(name string) (string, bool)

PathParam returns the named variables in the request.

func (*Context) QueryParam

func (c *Context) QueryParam(name string) (string, bool)

QueryParam returns the named query in the request.

func (*Context) Redirect

func (c *Context) Redirect(code int, location string) error

Redirect returns an HTTP redirect to the specific location.

func (*Context) RemoteIP

func (c *Context) RemoteIP() string

RemoteIP parses the IP from Request.RemoteAddr, normalizes and returns the IP (without the port).

func (*Context) Render

func (c *Context) Render(code int, render render.Renderer) error

Render writes the response headers and calls render.Render to render data.

func (*Context) RequestBody

func (c *Context) RequestBody() io.Reader

RequestBody returns the request body.

func (*Context) SetCookie

func (c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool)

SetCookie adds a Set-Cookie header to the ResponseWriter's headers. The provided cookie must have a valid Name. Invalid cookies may be silently dropped.

func (*Context) SetHeader

func (c *Context) SetHeader(key, value string)

SetHeader is an intelligent shortcut for c.Writer.Header().Set(key, value). It writes a header in the response. If value == "", this method removes the header `c.Writer.Header().Del(key)`

func (*Context) SetSameSite

func (c *Context) SetSameSite(samesite http.SameSite)

SetSameSite with cookie

func (*Context) Status

func (c *Context) Status(code int)

Status sets the HTTP response code.

func (*Context) String

func (c *Context) String(code int, format string, args ...interface{}) error

String writes the given string into the response body.

func (*Context) XML

func (c *Context) XML(code int, obj interface{}) error

XML serializes the given struct as XML into the response body. It also sets the Content-Type as "application/xml".

type HttpError

type HttpError struct {
	Code    int
	Message string
}

func Error

func Error(code int, format string, args ...interface{}) HttpError

func (HttpError) Error

func (e HttpError) Error() string

type MatcherFunc

type MatcherFunc = mux.MatcherFunc

MatcherFunc is the function signature used by custom matchers.

type MiddlewareFunc

type MiddlewareFunc = mux.MiddlewareFunc

MiddlewareFunc is a function which receives an http.Handler and returns another http.Handler. Typically, the returned handler is a closure which does something with the http.ResponseWriter and http.Request passed to it, and then calls the handler passed as parameter to the MiddlewareFunc.

type Options

type Options struct {
	// Addr optionally specifies the TCP address for the server to listen on,
	// in the form "host:port". If empty, ":http" (port 8080) is used.
	// The service names are defined in RFC 6335 and assigned by IANA.
	// See net.Dial for details of the address format.
	Addr string `value:"${addr:=}"`

	// CertFile containing a certificate and matching private key for the
	// server must be provided if neither the Server's
	// TLSConfig.Certificates nor TLSConfig.GetCertificate are populated.
	// If the certificate is signed by a certificate authority, the
	// certFile should be the concatenation of the server's certificate,
	// any intermediates, and the CA's certificate.
	CertFile string `value:"${cert-file:=}"`

	// KeyFile containing a private key file.
	KeyFile string `value:"${key-file:=}"`

	// ReadTimeout is the maximum duration for reading the entire
	// request, including the body. A zero or negative value means
	// there will be no timeout.
	//
	// Because ReadTimeout does not let Handlers make per-request
	// decisions on each request body's acceptable deadline or
	// upload rate, most users will prefer to use
	// ReadHeaderTimeout. It is valid to use them both.
	ReadTimeout time.Duration `value:"${read-timeout:=0s}"`

	// ReadHeaderTimeout is the amount of time allowed to read
	// request headers. The connection's read deadline is reset
	// after reading the headers and the Handler can decide what
	// is considered too slow for the body. If ReadHeaderTimeout
	// is zero, the value of ReadTimeout is used. If both are
	// zero, there is no timeout.
	ReadHeaderTimeout time.Duration `value:"${read-header-timeout:=0s}"`

	// WriteTimeout is the maximum duration before timing out
	// writes of the response. It is reset whenever a new
	// request's header is read. Like ReadTimeout, it does not
	// let Handlers make decisions on a per-request basis.
	// A zero or negative value means there will be no timeout.
	WriteTimeout time.Duration `value:"${write-timeout:=0s}"`

	// IdleTimeout is the maximum amount of time to wait for the
	// next request when keep-alives are enabled. If IdleTimeout
	// is zero, the value of ReadTimeout is used. If both are
	// zero, there is no timeout.
	IdleTimeout time.Duration `value:"${idle-timeout:=0s}"`

	// MaxHeaderBytes controls the maximum number of bytes the
	// server will read parsing the request header's keys and
	// values, including the request line. It does not limit the
	// size of the request body.
	// If zero, DefaultMaxHeaderBytes is used.
	MaxHeaderBytes int `value:"${max-header-bytes:=0}"`
}

func (Options) GetCertificate

func (options Options) GetCertificate(info *tls.ClientHelloInfo) (*tls.Certificate, error)

func (Options) IsTls

func (options Options) IsTls() bool

type Renderer

type Renderer interface {
	Render(ctx *Context, err error, result interface{})
}

type RendererFunc

type RendererFunc func(ctx *Context, err error, result interface{})

func (RendererFunc) Render

func (fn RendererFunc) Render(ctx *Context, err error, result interface{})

type Route

type Route = mux.Route

Route stores information to match a request and build URLs.

func CurrentRoute

func CurrentRoute(r *http.Request) *Route

CurrentRoute returns the matched route for the current request, if any. This only works when called inside the handler of the matched route because the matched route is stored in the request context which is cleared after the handler returns.

type RouteMatch

type RouteMatch = mux.RouteMatch

RouteMatch stores information about a matched route.

type Router

type Router = mux.Router

Router registers routes to be matched and dispatches a handler.

It implements the http.Handler interface, so it can be registered to serve requests:

var router = mux.NewRouter()

func main() {
    http.Handle("/", router)
}

Or, for Google App Engine, register it in a init() function:

func init() {
    http.Handle("/", router)
}

This will send all incoming requests to the router.

func NewRouter

func NewRouter() *Router

NewRouter returns a new router instance.

type Server

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

A Server defines parameters for running an HTTP server.

func NewServer

func NewServer(router *Router, options Options) *Server

NewServer returns a new server instance.

func (*Server) Addr

func (s *Server) Addr() string

Addr returns the server listen address.

func (*Server) Bind

func (s *Server) Bind(path string, handler interface{}, r ...Renderer) *Route

Bind registers a new route with a matcher for the URL path. Automatic binding request to handler input params, following functions:

func(ctx context.Context)

func(ctx context.Context) R

func(ctx context.Context) error

func(ctx context.Context, req T) R

func(ctx context.Context, req T) error

func(ctx context.Context, req T) (R, error)

func (*Server) BuildVarsFunc

func (s *Server) BuildVarsFunc(f BuildVarsFunc) *Route

BuildVarsFunc registers a new route with a custom function for modifying route variables before building a URL.

func (*Server) Connect

func (s *Server) Connect(path string, handler interface{}, r ...Renderer) *Route

Connect registers a new CONNECT route with a matcher for the URL path of the get method. See Server.Bind()

func (*Server) Delete

func (s *Server) Delete(path string, handler interface{}, r ...Renderer) *Route

Delete registers a new DELETE route with a matcher for the URL path of the get method. See Server.Bind()

func (*Server) Get

func (s *Server) Get(path string, handler interface{}, r ...Renderer) *Route

Get registers a new GET route with a matcher for the URL path of the get method. See Server.Bind()

func (*Server) GetRoute

func (s *Server) GetRoute(name string) *Route

GetRoute returns a route registered with the given name.

func (*Server) Handle

func (s *Server) Handle(path string, handler http.Handler) *Route

Handle registers a new route with a matcher for the URL path. See Route.Path() and Route.Handler().

func (*Server) HandleFunc

func (s *Server) HandleFunc(path string, f func(http.ResponseWriter, *http.Request)) *Route

HandleFunc registers a new route with a matcher for the URL path. See Route.Path() and Route.HandlerFunc().

func (*Server) Head

func (s *Server) Head(path string, handler interface{}, r ...Renderer) *Route

Head registers a new HEAD route with a matcher for the URL path of the get method. See Server.Bind()

func (*Server) Headers

func (s *Server) Headers(pairs ...string) *Route

Headers registers a new route with a matcher for request header values. See Route.Headers().

func (*Server) Match

func (s *Server) Match(req *http.Request, match *RouteMatch) bool

Match attempts to match the given request against the router's registered routes.

If the request matches a route of this router or one of its subrouters the Route, Handler, and Vars fields of the the match argument are filled and this function returns true.

If the request does not match any of this router's or its subrouters' routes then this function returns false. If available, a reason for the match failure will be filled in the match argument's MatchErr field. If the match failure type (eg: not found) has a registered handler, the handler is assigned to the Handler field of the match argument.

func (*Server) MatcherFunc

func (s *Server) MatcherFunc(f MatcherFunc) *Route

MatcherFunc registers a new route with a custom matcher function. See Route.MatcherFunc().

func (*Server) MethodNotAllowed

func (s *Server) MethodNotAllowed(handler http.Handler)

MethodNotAllowed to be used when the request method does not match the route. This can be used to render your own 405 Method Not Allowed errors.

func (*Server) Methods

func (s *Server) Methods(methods ...string) *Route

Methods registers a new route with a matcher for HTTP methods. See Route.Methods().

func (*Server) Name

func (s *Server) Name(name string) *Route

Name registers a new route with a name. See Route.Name().

func (*Server) NewRoute

func (s *Server) NewRoute() *Route

NewRoute registers an empty route.

func (*Server) NotFound

func (s *Server) NotFound(handler http.Handler)

NotFound to be used when no route matches. This can be used to render your own 404 Not Found errors.

func (*Server) Options

func (s *Server) Options(path string, handler interface{}, r ...Renderer) *Route

Options registers a new OPTIONS route with a matcher for the URL path of the get method. See Server.Bind()

func (*Server) Patch

func (s *Server) Patch(path string, handler interface{}, r ...Renderer) *Route

Patch registers a new PATCH route with a matcher for the URL path of the get method. See Server.Bind()

func (*Server) Path

func (s *Server) Path(tpl string) *Route

Path registers a new route with a matcher for the URL path. See Route.Path().

func (*Server) PathPrefix

func (s *Server) PathPrefix(tpl string) *Route

PathPrefix registers a new route with a matcher for the URL path prefix. See Route.PathPrefix().

func (*Server) Post

func (s *Server) Post(path string, handler interface{}, r ...Renderer) *Route

Post registers a new POST route with a matcher for the URL path of the get method. See Server.Bind()

func (*Server) Put

func (s *Server) Put(path string, handler interface{}, r ...Renderer) *Route

Put registers a new PUT route with a matcher for the URL path of the get method. See Server.Bind()

func (*Server) Queries

func (s *Server) Queries(pairs ...string) *Route

Queries registers a new route with a matcher for URL query values. See Route.Queries().

func (*Server) Renderer

func (s *Server) Renderer(renderer Renderer)

Renderer to be used Response renderer in default.

func (*Server) Router

func (s *Server) Router() *Router

Router returns the server router.

func (*Server) Run

func (s *Server) Run() error

Run listens on the TCP network address Addr and then calls Serve to handle requests on incoming connections. Accepted connections are configured to enable TCP keep-alives.

func (*Server) Schemes

func (s *Server) Schemes(schemes ...string) *Route

Schemes registers a new route with a matcher for URL schemes. See Route.Schemes().

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP dispatches the handler registered in the matched route.

When there is a match, the route variables can be retrieved calling Vars(request).

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the server without interrupting any active connections. Shutdown works by first closing all open listeners, then closing all idle connections, and then waiting indefinitely for connections to return to idle and then shut down. If the provided context expires before the shutdown is complete, Shutdown returns the context's error, otherwise it returns any error returned from closing the Server's underlying Listener(s).

func (*Server) SkipClean

func (s *Server) SkipClean(value bool)

SkipClean defines the path cleaning behaviour for new routes. The initial value is false. Users should be careful about which routes are not cleaned

When true, if the route path is "/path//to", it will remain with the double slash. This is helpful if you have a route like: /fetch/http://xkcd.com/534/

When false, the path will be cleaned, so /fetch/http://xkcd.com/534/ will become /fetch/http/xkcd.com/534

func (*Server) StrictSlash

func (s *Server) StrictSlash(value bool)

StrictSlash defines the trailing slash behavior for new routes. The initial value is false.

When true, if the route path is "/path/", accessing "/path" will perform a redirect to the former and vice versa. In other words, your application will always see the path as specified in the route.

When false, if the route path is "/path", accessing "/path/" will not match this route and vice versa.

The re-direct is a HTTP 301 (Moved Permanently). Note that when this is set for routes with a non-idempotent method (e.g. POST, PUT), the subsequent re-directed request will be made as a GET by most clients. Use middleware or client settings to modify this behaviour as needed.

Special case: when a route sets a path prefix using the PathPrefix() method, strict slash is ignored for that route because the redirect behavior can't be determined from a prefix alone. However, any subrouters created from that route inherit the original StrictSlash setting.

func (*Server) Trace

func (s *Server) Trace(path string, handler interface{}, r ...Renderer) *Route

Trace registers a new TRACE route with a matcher for the URL path of the get method. See Server.Bind()

func (*Server) Use

func (s *Server) Use(mwf ...MiddlewareFunc)

Use appends a MiddlewareFunc to the chain. Middleware can be used to intercept or otherwise modify requests and/or responses, and are executed in the order that they are applied to the Router.

func (*Server) UseEncodedPath

func (s *Server) UseEncodedPath()

UseEncodedPath tells the router to match the encoded original path to the routes. For eg. "/path/foo%2Fbar/to" will match the path "/path/{var}/to".

If not called, the router will match the unencoded path to the routes. For eg. "/path/foo%2Fbar/to" will match the path "/path/foo/bar/to"

func (*Server) Walk

func (s *Server) Walk(walkFn WalkFunc) error

Walk walks the router and all its sub-routers, calling walkFn for each route in the tree. The routes are walked in the order they were added. Sub-routers are explored depth-first.

type WalkFunc

type WalkFunc = mux.WalkFunc

WalkFunc is the type of the function called for each route visited by Walk. At every invocation, it is given the current route, and the current router, and a list of ancestor routes that lead to the current route.

Directories

Path Synopsis
Package binding ...
Package binding ...

Jump to

Keyboard shortcuts

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