lungo

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Mar 25, 2022 License: MIT Imports: 16 Imported by: 0

README

Lungo

A tiny, zero-dependency web framework based on net/http with an intuitive API.

Issues Stars License Stars Issues Twitter

Quickstart

package main

import "github.com/felix-kaestner/lungo"

func main() {
    app := lungo.New()

    app.Get("/", func(c *lungo.Context) error {
        return c.Text("Hello, World!")
    })

    app.Listen(":3000")
}

Installation

Install Lungo with the go get command:

$ go get -u github.com/felix-kaestner/lungo

Contribute

All contributions in any form are welcome! 🙌
Just use the Issue and Pull Request templates and I will be happy to review your suggestions. 👍

Support

Any kind of support is well appreciated! 👏
If you want to tweet about the project, make sure to tag me @kaestner_felix. You can also support my open source work on GitHub Sponsors. All income will be directly invested in Coffee (specifically Lungo) ☕!

Cheers ✌

Documentation

Index

Constants

View Source
const (
	// Version of Lungo
	Version = "1.0.1"

	// Website of Lungo
	Website = "https://github.com/felix-kaestner/lungo"

	// Header - RFC 4229
	HeaderAIM                     = "A-IM"
	HeaderAccept                  = "Accept"
	HeaderAcceptAdditions         = "Accept-Additions"
	HeaderAcceptCharset           = "Accept-Charset"
	HeaderAcceptEncoding          = "Accept-Encoding"
	HeaderAcceptFeatures          = "Accept-Features"
	HeaderAcceptLanguage          = "Accept-Language"
	HeaderAcceptRanges            = "Accept-Ranges"
	HeaderAge                     = "Age"
	HeaderAllow                   = "Allow"
	HeaderAlternates              = "Alternates"
	HeaderAuthenticationInfo      = "Authentication-Info"
	HeaderAuthorization           = "Authorization"
	HeaderCExt                    = "C-Ext"
	HeaderCMan                    = "C-Man"
	HeaderCOpt                    = "C-Opt"
	HeaderCPEP                    = "C-PEP"
	HeaderCPEPInfo                = "C-PEP-Info"
	HeaderCacheControl            = "Cache-Control"
	HeaderConnection              = "Connection"
	HeaderContentBase             = "Content-Base"
	HeaderContentDisposition      = "Content-Disposition"
	HeaderContentEncoding         = "Content-Encoding"
	HeaderContentID               = "Content-ID"
	HeaderContentLanguage         = "Content-Language"
	HeaderContentLength           = "Content-Length"
	HeaderContentLocation         = "Content-Location"
	HeaderContentMD5              = "Content-MD5"
	HeaderContentRange            = "Content-Range"
	HeaderContentScriptType       = "Content-Script-Type"
	HeaderContentStyleType        = "Content-Style-Type"
	HeaderContentType             = "Content-Type"
	HeaderContentVersion          = "Content-Version"
	HeaderCookie                  = "Cookie"
	HeaderCookie2                 = "Cookie2"
	HeaderDAV                     = "DAV"
	HeaderDate                    = "Date"
	HeaderDefaultStyle            = "Default-Style"
	HeaderDeltaBase               = "Delta-Base"
	HeaderDepth                   = "Depth"
	HeaderDerivedFrom             = "Derived-From"
	HeaderDestination             = "Destination"
	HeaderDifferentialID          = "Differential-ID"
	HeaderDigest                  = "Digest"
	HeaderETag                    = "ETag"
	HeaderExpect                  = "Expect"
	HeaderExpires                 = "Expires"
	HeaderExt                     = "Ext"
	HeaderFrom                    = "From"
	HeaderGetProfile              = "GetProfile"
	HeaderHost                    = "Host"
	HeaderIM                      = "IM"
	HeaderIf                      = "If"
	HeaderIfMatch                 = "If-Match"
	HeaderIfModifiedSince         = "If-Modified-Since"
	HeaderIfNoneMatch             = "If-None-Match"
	HeaderIfRange                 = "If-Range"
	HeaderIfUnmodifiedSince       = "If-Unmodified-Since"
	HeaderKeepAlive               = "Keep-Alive"
	HeaderLabel                   = "Label"
	HeaderLastModified            = "Last-Modified"
	HeaderLink                    = "Link"
	HeaderLocation                = "Location"
	HeaderLockToken               = "Lock-Token"
	HeaderMIMEVersion             = "MIME-Version"
	HeaderMan                     = "Man"
	HeaderMaxForwards             = "Max-Forwards"
	HeaderMeter                   = "Meter"
	HeaderNegotiate               = "Negotiate"
	HeaderOpt                     = "Opt"
	HeaderOrderingType            = "Ordering-Type"
	HeaderOrigin                  = "Origin"
	HeaderOverwrite               = "Overwrite"
	HeaderP3P                     = "P3P"
	HeaderPEP                     = "PEP"
	HeaderPICSLabel               = "PICS-Label"
	HeaderPepInfo                 = "Pep-Info"
	HeaderPosition                = "Position"
	HeaderPragma                  = "Pragma"
	HeaderProfileObject           = "ProfileObject"
	HeaderProtocol                = "Protocol"
	HeaderProtocolInfo            = "Protocol-Info"
	HeaderProtocolQuery           = "Protocol-Query"
	HeaderProtocolRequest         = "Protocol-Request"
	HeaderProxyAuthenticate       = "Proxy-Authenticate"
	HeaderProxyAuthenticationInfo = "Proxy-Authentication-Info"
	HeaderProxyAuthorization      = "Proxy-Authorization"
	HeaderProxyFeatures           = "Proxy-Features"
	HeaderProxyInstruction        = "Proxy-Instruction"
	HeaderPublic                  = "Public"
	HeaderRange                   = "Range"
	HeaderReferer                 = "Referer"
	HeaderRetryAfter              = "Retry-After"
	HeaderSafe                    = "Safe"
	HeaderSecurityScheme          = "Security-Scheme"
	HeaderServer                  = "Server"
	HeaderSetCookie               = "Set-Cookie"
	HeaderSetCookie2              = "Set-Cookie2"
	HeaderSetProfile              = "SetProfile"
	HeaderSoapAction              = "SoapAction"
	HeaderStatusURI               = "Status-URI"
	HeaderSurrogateCapability     = "Surrogate-Capability"
	HeaderSurrogateControl        = "Surrogate-Control"
	HeaderTCN                     = "TCN"
	HeaderTE                      = "TE"
	HeaderTimeout                 = "Timeout"
	HeaderTrailer                 = "Trailer"
	HeaderTransferEncoding        = "Transfer-Encoding"
	HeaderURI                     = "URI"
	HeaderUpgrade                 = "Upgrade"
	HeaderUserAgent               = "User-Agent"
	HeaderVariantVary             = "Variant-Vary"
	HeaderVary                    = "Vary"
	HeaderVia                     = "Via"
	HeaderWWWAuthenticate         = "WWW-Authenticate"
	HeaderWantDigest              = "Want-Digest"
	HeaderWarning                 = "Warning"
	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"

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

	// Security
	HeaderContentSecurityPolicy           = "Content-Security-Policy"
	HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only"
	HeaderReferrerPolicy                  = "Referrer-Policy"
	HeaderStrictTransportSecurity         = "Strict-Transport-Security"
	HeaderXContentTypeOptions             = "X-Content-Type-Options"
	HeaderXFrameOptions                   = "X-Frame-Options"
	HeaderXXSSProtection                  = "X-XSS-Protection"
	HeaderXCSRFToken                      = "X-CSRF-Token"

	// Charset
	CharsetUTF8 = "charset=utf-8"

	// MIME types
	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"
)
View Source
const (
	// ErrInvalidRouteMethod is returned when the route method is invalid.
	ErrInvalidRouteMethod = "Invalid method. The method of a handler must be a valid http method."
	// ErrEmptyRoutePath is returned when the route path is empty.
	ErrEmptyRoutePath = "Invalid pattern. The path of a handler can't be empty."
	// ErrNilRouteHandler is returned when the route handler is nil.
	ErrNilRouteHandler = "Nil handler. The handler can't be nil."
	// ErrDuplicateHandler is returned when a route handler is already registered for a given path.
	ErrDuplicateHandler = "Duplicate path. Path `%s` already contains a http handler."
)
View Source
const (
	// DefaultMaxBodySize defines the default maximum number of bytes
	// to read from a http request body.
	DefaultMaxBodySize = 1048576 // 1 * 1024 * 1024 = 1048576 Bytes = 1MiB
)

Variables

View Source
var ContextKey = &struct{}{}

ContextKey defines the key to retrieve the Lungo context context from the request context

Functions

func Canonical

func Canonical(p string) string

Canonical returns a canonical path for p, eliminating . and .. elements.

func IsValidMethod

func IsValidMethod(method string) bool

IsValidMethod checks if the provided http method is valid

Types

type App

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

App is the top-level application instance

func New

func New(configure ...func(*Config)) (app *App)

New creates an instance of App.

func (*App) AcquireContext

func (app *App) AcquireContext() *Context

AcquireContext acquires a empty context instance from the pool. This context instance must be released by calling `ReleaseContext()`.

func (*App) All

func (app *App) All(path string, handler HandlerFunc)

All adds a new Route on all HTTP methods to the Router of the application.

func (*App) Config

func (app *App) Config() *Config

Config returns the Config instance of the application

func (*App) Connect

func (app *App) Connect(path string, handler HandlerFunc)

Connect adds a new Route with http method "CONNECT" to the Router of the application.

func (*App) Delete

func (app *App) Delete(path string, handler HandlerFunc)

Delete adds a new Route with http method "DELETE" to the Router of the application.

func (*App) Get

func (app *App) Get(path string, handler HandlerFunc)

Get adds a new Route with http method "GET" to the Router of the application.

func (*App) Handle

func (app *App) Handle(method, path string, handler HandlerFunc)

Handle adds a new Route with the specified http method to the Router of the application.

func (*App) HandleError

func (app *App) HandleError(c *Context, e error)

HandleError is a centralized error handler function which resolves the provided error and replies to the request with the specified error message and HTTP code. The error message is written as plain text. JSON response with status code and message.

func (*App) Head

func (app *App) Head(path string, handler HandlerFunc)

Head adds a new Route with http method "HEAD" to the Router of the application.

func (*App) Listen

func (app *App) Listen(addr string) error

Listen listens on the TCP network address addr and then calls Serve with handler to handle requests on incoming connections. Accepted connections are configured to enable TCP keep-alives.

The handler is typically nil, in which case the DefaultServeMux is used.

ListenAndServe always returns a non-nil error.

func (*App) ListenTLS

func (app *App) ListenTLS(addr, certFile, keyFile string) error

ListenTLS acts identically to Listen, except that it expects HTTPS connections. Additionally, files containing a certificate and matching private key for the server must be provided. 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.

func (*App) Mount

func (app *App) Mount(pattern string, group *App)

Mount adds a new app which handles requests on the specified pattern.

func (*App) NewContext

func (app *App) NewContext(w http.ResponseWriter, r *http.Request) *Context

NewContext returns a new Context instance.

It serves as an adapter for http.Handlerfunc and converts the request to the context based API provided by Lungo.

func (*App) Options

func (app *App) Options(path string, handler HandlerFunc)

Options adds a new Route with http method "OPTIONS" to the Router of the application.

func (*App) Patch

func (app *App) Patch(path string, handler HandlerFunc)

Patch adds a new Route with http method "PATCH" to the Router of the application.

func (*App) Post

func (app *App) Post(path string, handler HandlerFunc)

Post adds a new Route with http method "POST" to the Router of the application.

func (*App) Put

func (app *App) Put(path string, handler HandlerFunc)

Put adds a new Route with http method "PUT" to the Router of the application.

func (*App) ReleaseContext

func (app *App) ReleaseContext(c *Context)

ReleaseContext releases the context instance back to the pool. The context instace must first be acquired by calling `AcquireContext()`.

func (*App) Serve

func (app *App) Serve(l net.Listener) error

Serve accepts incoming HTTP connections on the listener l, creating a new service goroutine for each. The service goroutines read requests and then call handler to reply to them.

The handler is typically nil, in which case the DefaultServeMux is used.

HTTP/2 support is only enabled if the Listener returns *tls.Conn connections and they were configured with "h2" in the TLS Config.NextProtos.

Serve always returns a non-nil error.

func (*App) ServeHTTP

func (app *App) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements the http.Handler interface which is used by the http.Server to dispatch requests.

It serves as an adapter for http.Handler and converts the request to the context based API provided by Lungo.

func (*App) ServeTLS

func (app *App) ServeTLS(l net.Listener, certFile, keyFile string) error

ServeTLS accepts incoming HTTPS connections on the listener l, creating a new service goroutine for each. The service goroutines read requests and then call handler to reply to them.

The handler is typically nil, in which case the DefaultServeMux is used.

Additionally, files containing a certificate and matching private key for the server must be provided. 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.

ServeTLS always returns a non-nil error.

func (*App) Server

func (app *App) Server() *http.Server

Server returns the http.Server instance of the application

func (*App) Shutdown

func (app *App) 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).

When Shutdown is called, Serve, ListenAndServe, and ListenAndServeTLS immediately return ErrServerClosed. Make sure the program doesn't exit and waits instead for Shutdown to return.

Shutdown does not attempt to close nor wait for hijacked connections such as WebSockets. The caller of Shutdown should separately notify such long-lived connections of shutdown and wait for them to close, if desired. See RegisterOnShutdown for a way to register shutdown notification functions.

Once Shutdown has been called on a server, it may not be reused; future calls to methods such as Serve will return ErrServerClosed.

func (*App) Static

func (app *App) Static(path, root string)

Static adds a new Route to the Router of the application, which serves static files.

func (*App) Trace

func (app *App) Trace(path string, handler HandlerFunc)

Trace adds a new Route with http method "TRACE" to the Router of the application.

func (*App) Use

func (app *App) Use(middlewares ...Middleware)

Use adds a Middleware to the router. Middleware can be used to intercept or otherwise modify requests. The are executed in the order that they are applied to the Router (FIFO).

type Config

type Config struct {
	// Maximum number of  bytes to read from the request body.
	// A request body larger than that will result in returning
	// a "http: request body too large" error.
	//
	// Set this value to -1 to allow all arbitrary large request bodies.
	//
	// Default: 1 * 1024 * 1024 = 1048576 Bytes = 1MiB
	MaxBodySize int `json:"max_body_size"`
}

Config defines the configuration options for the application

type Context

type Context struct {
	App      *App                `json:"-"`
	Request  *http.Request       `json:"-"`
	Response http.ResponseWriter `json:"-"`
	Params   url.Values          `json:"params"`
}

Context represents the context of a request, including request, response, path, parameters, headers and handler for common operations.

func (*Context) AddHeader

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

AddHeader adds the key, value pair to the header. It appends to any existing values associated with key. The key is case insensitive; it is canonicalized by CanonicalHeaderKey.

func (*Context) AddParam

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

AddParam adds the value to the parameter's values. It appends to any existing values associated with key.

func (*Context) Cookie

func (c *Context) Cookie(name string) (*http.Cookie, error)

Cookie returns the named cookie provided in the request or ErrNoCookie if not found. If multiple cookies match the given name, only one cookie will be returned.

func (*Context) Cookies

func (c *Context) Cookies() []*http.Cookie

Cookies parses and returns the HTTP cookies sent with the request.

func (*Context) DecodeJSONBody

func (c *Context) DecodeJSONBody(dst interface{}) error

DecodeJSONBody decodes an object with a given interface from a JSON request body.

func (*Context) DeleteParam

func (c *Context) DeleteParam(key string)

DeleteParam deletes the values associated with the parameter.

func (*Context) Error

func (c *Context) Error(code int) (err error)

Error dispatches a error response. Use the method parameter `code` to set status code of the response. The message will automatically be set to the corresponding http.StatusText.

func (*Context) Errorf

func (c *Context) Errorf(code int, message interface{}) (err error)

Errorf dispatches a error response with custom message. Use the method parameter `code` to set status code of the response. Use the method parameter `message` to set the message of the response.

func (*Context) File

func (c *Context) File(name string) (err error)

File dispatches a response serving a file. Use the method parameter `name` to supply the filename.

func (*Context) Flush

func (c *Context) 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 (*Context) Header

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

Header gets the first value associated with the given key. If there are no values associated with the key, it returns "". It is case insensitive; textproto.CanonicalMIMEHeaderKey is used to canonicalize the provided key. To use non-canonical keys, access the map directly.

func (*Context) Hijack

func (c *Context) 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 (*Context) Json

func (c *Context) Json(code int, value interface{}) (err error)

Json dispatches a JSON response. Use the method parameter `code` to set the header status code. Use the method parameter `value` to supply the object to be serialized to JSON.

func (*Context) Method

func (c *Context) Method() string

Method specifies the HTTP method (GET, POST, PUT, etc.). For client requests, an empty string means GET.

Go's HTTP client does not support sending a request with the CONNECT method. See the documentation on Transport for details.

func (*Context) NoContent

func (c *Context) NoContent() (err error)

NoContent dispatchss an empty response with an HTTP 204 status code.

func (*Context) NotFound

func (c *Context) NotFound() error

NotFound replies to the request with an HTTP 404 not found error.

func (*Context) Param

func (c *Context) Param(key string) string

Param gets the first value associated with the given parameter. If there are no values associated with the key, Get returns the empty string. To access multiple values, use the map directly.

func (*Context) ParamOrDefault

func (c *Context) ParamOrDefault(key, val string) string

ParamOrDefault gets the first value associated with the given parameter or the provided default value if there are no values associated with the key.

func (*Context) ParseMediaType

func (c *Context) ParseMediaType() (mediatype string, params map[string]string, err error)

ParseMediaType parses a media type value and any optional parameters, per RFC 1521. Media types are the values in Content-Type and Content-Disposition headers (RFC 2183). On success, ParseMediaType returns the media type converted to lowercase and trimmed of white space and a non-nil map. If there is an error parsing the optional parameter, the media type will be returned along with the error ErrInvalidMediaParameter. The returned map, params, maps from the lowercase attribute to the attribute value with its case preserved.

func (*Context) Path

func (c *Context) Path() string

Path specifies either the URI being requested (for server requests) or the URL to access (for client requests).

For server requests, the URL is parsed from the URI supplied on the Request-Line as stored in RequestURI. For most requests, fields other than Path and RawQuery will be empty. (See RFC 7230, Section 5.3)

For client requests, the URL's Host specifies the server to connect to, while the Request's Host field optionally specifies the Host header value to send in the HTTP request.

func (*Context) Reset

func (c *Context) Reset(w http.ResponseWriter, r *http.Request)

Reset applies the given request to the Context instance.

The `App` property is assumed to be static, thus it will not be changed.

func (*Context) SetCookie

func (c *Context) SetCookie(cookie *http.Cookie)

SetCookie adds a Set-Cookie header to the provided 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 sets the header entries associated with key to the single element value. It replaces any existing values associated with key. The key is case insensitive; it is canonicalized by textproto.CanonicalMIMEHeaderKey. To use non-canonical keys, assign to the map directly.

func (*Context) SetParam

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

SetParam sets the parameter value. It replaces any existing values.

func (*Context) Text

func (c *Context) Text(code int, value interface{}) (err error)

Text dispatches a text response. Use the method parameter `code` to set the header status code. Use the method parameter `value` to supply the object to be serialized to text.

func (*Context) WriteHeader

func (c *Context) WriteHeader(code int)

WriteHeader sends an HTTP response header with the provided 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.

The provided code must be a valid HTTP 1xx-5xx status code. Only one header may be written. Go does not currently support sending user-defined 1xx informational headers, with the exception of 100-continue response header that the Server sends automatically when the Request.Body is read.

type Handler

type Handler interface {
	ServeHTTP(c *Context) error
}

Handler is the generic interface for responding to an HTTP request.

ServeHTTP should write reply headers and data to the ResponseWriter and then return. Returning signals that the request is finished; it is not valid to use the ResponseWriter or read from the Request.Body after or concurrently with the completion of the ServeHTTP call.

Depending on the HTTP client software, HTTP protocol version, and any intermediaries between the client and the Go server, it may not be possible to read from the Request.Body after writing to the ResponseWriter. Cautious handlers should read the Request.Body first, and then reply.

Except for reading the body, handlers should not modify the provided Request.

If ServeHTTP panics, the server (the caller of ServeHTTP) assumes that the effect of the panic was isolated to the active request. It recovers the panic, logs a stack trace to the server error log, and either closes the network connection or sends an HTTP/2 RST_STREAM, depending on the HTTP protocol. To abort a handler so the client sees an interrupted response but the server doesn't log an error, panic with the value ErrAbortHandler.

func FileHandler

func FileHandler(root string) Handler

FileHandler creates a new Handler that serves static files in a directory.

func NotFoundHandler

func NotFoundHandler() Handler

NotFoundHandler returns a simple request handler that replies to each request with a `Not Found` reply.

func RedirectHandler

func RedirectHandler(url string, code int) Handler

RedirectHandler creates a new Handler that redirects requests it receives to a given URL using the provided status code.

The provided status code should be in the 3xx range and is usually http.StatusMovedPermanently, http.StatusFound or http.StatusSeeOther.

type HandlerFunc

type HandlerFunc func(c *Context) error

HandlerFunc is the type of an adapter to allow the use of ordinary functions as HTTP handlers. If f is a function with the appropriate signature, HandlerFunc(f) is a Handler that calls f.

func WithContext

func WithContext(handler http.Handler) HandlerFunc

WithContext is an adapter to allow the usage of http.Handler with the context based API provided by Lungo

func (HandlerFunc) ServeHTTP

func (h HandlerFunc) ServeHTTP(c *Context) error

ServeHTTP implements the Handler interface for HandlerFunc by simply returning the function call with the provided context

type Map

type Map map[string]interface{}

Map is a shorthand of type `map[string]interface{}`.

type Middleware

type Middleware func(Handler) Handler

Middleware is a function which receives an Handler and returns another Handler.

type Redirect

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

Redirect to a fixed URL

func (*Redirect) ServeHTTP

func (redirect *Redirect) ServeHTTP(c *Context) error

`ServeHTTP` implements the Handler interface

type RequestError

type RequestError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

RequestError stores information about errors during the handling a request. The provided code must be a valid HTTP 1xx-5xx status code.

func (*RequestError) Error

func (e *RequestError) Error() string

`Error` implements the error interface

type Route

type Route struct {
	Method  string  `json:"method"`
	Path    string  `json:"path"`
	Handler Handler `json:"-"`
}

Route stores information to match and respond to requests.

func (*Route) ServeHTTP

func (route *Route) ServeHTTP(c *Context) error

`ServeHTTP` implements the Handler interface

type Router

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

Router is an HTTP request multiplexer.

func NewRouter

func NewRouter() *Router

NewRouter allocates and returns a new router instance.

func (*Router) Handle

func (router *Router) Handle(route Route)

Handle registers a Handler for the given path. This will panic, if the path already has a Handler registered.

func (*Router) Handler

func (router *Router) Handler(r *http.Request) Handler

Handler returns the Handler to use for the given http request.

If the path of the request is not in canonical form, then the returned handler will be a redirect to the canonical path.

If no handler matches the given request, then the return will be a `Error 404: page not found` Handler.

func (*Router) ServeHTTP

func (router *Router) ServeHTTP(c *Context) error

`ServeHTTP` implements the Handler interface. It handles the http request and dispatches it to the request handler whose path matches the request URL.

func (*Router) Use

func (router *Router) Use(middlewares ...Middleware)

Use adds a Middleware to the router. Middleware can be used to intercept or otherwise modify requests. The are executed in the order that they are applied to the Router (FIFO).

Directories

Path Synopsis
middleware

Jump to

Keyboard shortcuts

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