web

package
v0.0.0-...-c18a219 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2023 License: MIT Imports: 33 Imported by: 13

Documentation

Overview

Package web implement a lightweight HTTP server.

Index

Constants

View Source
const (
	AuthAnonymous     = "*" // everyone
	AuthAuthenticated = "?" // logged-in users
	AuthAdministrator = "!" // administrators
)
View Source
const (
	MIMEApplicationJSON                  = "application/json"
	MIMEApplicationJSONCharsetUTF8       = MIMEApplicationJSON + "; " + charsetUTF8
	MIMEApplicationJavaScript            = "application/javascript"
	MIMEApplicationJavaScriptCharsetUTF8 = MIMEApplicationJavaScript + "; " + charsetUTF8
	MIMEApplicationXML                   = "application/xml"
	MIMEApplicationXMLCharsetUTF8        = MIMEApplicationXML + "; " + charsetUTF8
	MIMEApplicationForm                  = "application/x-www-form-urlencoded"
	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 (
	HeaderAcceptEncoding      = "Accept-Encoding"
	HeaderAcceptLanguage      = "Accept-Language"
	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"
	HeaderXForwardedProto     = "X-Forwarded-Proto"
	HeaderXHTTPMethodOverride = "X-HTTP-Method-Override"
	HeaderXForwardedFor       = "X-Forwarded-For"
	HeaderXRealIP             = "X-Real-IP"
	HeaderXRequestedWith      = "X-Requested-With"
	HeaderServer              = "Server"
	HeaderOrigin              = "Origin"
	HeaderExpires             = "Expires"
	HeaderCacheControl        = "Cache-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"

	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 (
	DispositionAttachment = "attachment"
	DispositionInline     = "inline"
)
View Source
const PkgName = "auxo.net.web"

Variables

View Source
var (
	ErrUnauthorized           = NewError(http.StatusUnauthorized)
	ErrForbidden              = NewError(http.StatusForbidden)
	ErrNotFound               = NewError(http.StatusNotFound)
	ErrMethodNotAllowed       = NewError(http.StatusMethodNotAllowed)
	ErrUnsupportedMediaType   = NewError(http.StatusUnsupportedMediaType)
	ErrInternalServerError    = NewError(http.StatusInternalServerError)
	ErrRendererNotRegistered  = errors.New("Renderer not registered")
	ErrBinderNotRegistered    = errors.New("Binder not registered")
	ErrValidatorNotRegistered = errors.New("Validator not registered")
	ErrInvalidRedirectCode    = errors.New("Invalid redirect status code")
)

Errors

Functions

This section is empty.

Types

type Binder

type Binder interface {
	// Bind takes data out of the request and decodes into a struct according
	// to the Content-Type of the request.
	Bind(ctx Context, i interface{}) (err error)
}

Binder is the interface that can unmarshal request data to struct.

type ContentDisposition

type ContentDisposition struct {
	Type string
	Name string
}

type Context

type Context interface {
	// Reset resets the context after request completes. It must be called along
	// with `Server#AcquireContext()` and `Server#ReleaseContext()`.
	// See `Server#ServeHTTP()`
	Reset(r *http.Request, w http.ResponseWriter)

	// Server returns the `Server` instance.
	Server() *Server

	// Logger returns the `Logger` instance.
	Logger() log.Logger

	// User returns info of current visitor.
	User() User

	// SetUser set user info of current visitor. Generally used by authentication filter.
	SetUser(user User)

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

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

	// Bind binds the request body into `i`.
	// Validator must be registered using `Server#Validator` if validate arg is true.
	Bind(i interface{}, validate ...bool) error

	// Route returns the registered route path for current handler.
	Route() string

	// Handler returns the matched handler info by router.
	Handler() HandlerInfo

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

	Requester

	Responser
}

Context represents the context of the current HTTP request.

type Entry

type Entry struct {
	Address string // http://:8001,https://auxo.net:443,unix:///a/b
	TLS     *struct {
		Cert string
		Key  string
		ACME *struct {
			//Server string // default: https://acme-staging.api.letsencrypt.org/directory
			Domain   string
			Email    string
			CacheDir string
		}
	}
}

Entry represents an entry-point for listening.

type Error

type Error errors.CodedError

Error represents an HTTP error occurred while handling a request.

func NewError

func NewError(code int, msg ...string) *Error

NewError creates a new Error instance.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Status

func (e *Error) Status() int

type ErrorHandler

type ErrorHandler struct {
	Detail  bool
	Default ErrorHandlerFunc
	// contains filtered or unexported fields
}

func (*ErrorHandler) OnCode

func (h *ErrorHandler) OnCode(code int, fn ErrorHandlerFunc)

func (*ErrorHandler) OnError

func (h *ErrorHandler) OnError(t reflect.Type, fn ErrorHandlerFunc)

func (*ErrorHandler) OnType

func (h *ErrorHandler) OnType(ct string, fn ErrorHandlerFunc)

type ErrorHandlerFunc

type ErrorHandlerFunc func(Context, error)

type Filter

type Filter interface {
	Apply(HandlerFunc) HandlerFunc
}

Filter defines a filter interface.

func WrapFilter

func WrapFilter(f func(http.Handler) http.Handler) Filter

WrapFilter wraps `func(http.Handler) http.Handler` into `web.FilterFunc`

type FilterFunc

type FilterFunc func(HandlerFunc) HandlerFunc

FilterFunc defines a filter function type.

func (FilterFunc) Apply

func (f FilterFunc) Apply(h HandlerFunc) HandlerFunc

type Group

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

Group is a set of sub-routes which is associated with a prefix and shares filters.

func (*Group) Any

func (g *Group) Any(path string, handler HandlerFunc, opts ...HandlerOption)

Any registers a route that matches all the HTTP methods.

func (*Group) Connect

func (g *Group) Connect(path string, h HandlerFunc, opts ...HandlerOption)

Connect registers a route that matches 'CONNECT' method.

func (*Group) Delete

func (g *Group) Delete(path string, h HandlerFunc, opts ...HandlerOption)

Delete registers a route that matches 'DELETE' method.

func (*Group) File

func (g *Group) File(path string, fs http.FileSystem, name string, filters ...Filter)

File registers a route in order to server a single file of the local filesystem.

func (*Group) Get

func (g *Group) Get(path string, h HandlerFunc, opts ...HandlerOption)

Get registers a route that matches 'GET' method.

func (*Group) Group

func (g *Group) Group(prefix string, filters ...Filter) *Group

Group creates a new router group.

func (*Group) Handle

func (g *Group) Handle(path string, controller interface{}, filters ...Filter)

Handle registers routes from controller. It panics if controller's Kind is not Struct.

func (*Group) Head

func (g *Group) Head(path string, h HandlerFunc, opts ...HandlerOption)

Head registers a route that matches 'HEAD' method.

func (*Group) Match

func (g *Group) Match(methods []string, path string, handler HandlerFunc, opts ...HandlerOption)

Match registers a route that matches specific methods.

func (*Group) Options

func (g *Group) Options(path string, h HandlerFunc, opts ...HandlerOption)

Options registers a route that matches 'OPTIONS' method.

func (*Group) Patch

func (g *Group) Patch(path string, h HandlerFunc, opts ...HandlerOption)

Patch registers a route that matches 'PATCH' method.

func (*Group) Post

func (g *Group) Post(path string, h HandlerFunc, opts ...HandlerOption)

Post registers a route that matches 'POST' method.

func (*Group) Put

func (g *Group) Put(path string, h HandlerFunc, opts ...HandlerOption)

Put registers a route that matches 'PUT' method.

func (*Group) Static

func (g *Group) Static(prefix string, fs http.FileSystem, fallback string, filters ...Filter)

Static serves static files from a custom file system.

func (*Group) Trace

func (g *Group) Trace(path string, h HandlerFunc, opts ...HandlerOption)

Trace registers a route that matches 'TRACE' method.

func (*Group) Use

func (g *Group) Use(filters ...Filter)

Use adds filters to the group routes.

func (*Group) UseFunc

func (g *Group) UseFunc(filters ...FilterFunc)

UseFunc adds filters to the router.

type HandlerFunc

type HandlerFunc func(Context) error

HandlerFunc defines a function to server HTTP requests.

func WrapError

func WrapError(err *Error) HandlerFunc

WrapError wraps an `Error` into `web.HandlerFunc`.

func WrapFile

func WrapFile(fs http.FileSystem, name string) HandlerFunc

func WrapFileSystem

func WrapFileSystem(sys http.FileSystem, fallback string) HandlerFunc

func WrapHandler

func WrapHandler(h http.Handler) HandlerFunc

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

func (HandlerFunc) Chain

func (h HandlerFunc) Chain(filters ...Filter) HandlerFunc

type HandlerInfo

type HandlerInfo interface {
	Action() HandlerFunc
	Name() string
	Authorize() string
	Option(name string) string
}

HandlerInfo is the interface for handler info.

type HandlerOption

type HandlerOption func(*handlerInfo)

func WithAuthorize

func WithAuthorize(authorize string) HandlerOption

func WithFilter

func WithFilter(filters ...Filter) HandlerOption

func WithFilterFunc

func WithFilterFunc(filters ...FilterFunc) HandlerOption

func WithName

func WithName(name string) HandlerOption

func WithOption

func WithOption(name, value string) HandlerOption

type Options

type Options struct {
	// Name is used as HTTP `Server` header, default is auxo/[auxo.Version]
	Name                  string
	Mode                  string // develop/release
	Entries               []Entry
	RedirectTrailingSlash bool
	MethodNotAllowed      bool
	ReadTimeout           time.Duration
	ReadHeaderTimeout     time.Duration
	WriteTimeout          time.Duration
	IdleTimeout           time.Duration
	MaxHeaderSize         size.Size
	MaxBodySize           size.Size
	Authorize             string   // default authorize
	IndexPages            []string // static index pages, default: index.html

}

Options represents the options of Server.

type Renderer

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

Renderer is the interface that render HTML template.

type Requester

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

	// SetRequest replace default `*http.Request`.
	SetRequest(r *http.Request)

	// IsTLS returns true if HTTP connection is TLS otherwise false.
	IsTLS() bool

	// Scheme returns the HTTP protocol scheme, `http` or `https`.
	Scheme() string

	// RealIP returns the client's network address based on `X-Forwarded-For`
	// or `X-Real-IP` request header.
	RealIP() string

	// IsAJAX returns true if this request is an AJAX request(XMLHttpRequest)
	IsAJAX() bool

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

	// P returns path parameter by name, it's an alias of Path method.
	P(name string) string

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

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

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

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

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

	// Q returns the query param for the provided name, it's an alias of Query method.
	Q(name string) string

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

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

	// F returns the form field value for the provided name, it's an alias of Form method.
	F(name string) string

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

	// File returns the multipart form file for the provided name.
	File(name string) (multipart.File, *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)

	// Header returns request's header by name.
	Header(name string) string

	// ContentType returns the 'Content-Type' header of request. Charset is omited.
	ContentType() string
}

Requester holds all methods for reading request.

type ResponseWriter

type ResponseWriter interface {
	http.ResponseWriter
	http.Flusher
	http.Hijacker
	http.Pusher
	WriteString(s string) (n int, err error)
	Committed() bool
	Size() int
	Status() int
}

ResponseWriter wraps an http.ResponseWriter and implements its interface to be used by an HTTP handler to construct an HTTP response.

type Responser

type Responser interface {
	// Response returns `ResponseWriter`.
	Response() ResponseWriter

	// Status set status code of response.
	Status(code int) Responser

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

	// SetHeader writes given key and value to the response's header.
	SetHeader(key, value string) Responser

	// SetContentType sets the 'Content-Type' header of response.
	SetContentType(ct string) Responser

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

	// HTML sends an text/html response.
	HTML(html string) error

	// JSON sends a JSON response.
	JSON(i interface{}, indent ...string) error

	// JSONP sends a JSONP response. It uses `callback` to construct the JSONP payload.
	JSONP(callback string, i interface{}) error

	Result(code int32, info string, data interface{}) error

	// XML sends an XML response.
	XML(i interface{}, indent ...string) error

	// Text sends string as plain text.
	Text(s string) error

	// Data sends byte array to response.
	// You can use `Context.SetContentType` to set content type.
	Data(b []byte, cd ...ContentDisposition) error

	// Stream sends a streaming response.
	// You can use `Context.SetContentType` to set content type.
	Stream(r io.Reader, cd ...ContentDisposition) error

	// Content sends a response with the content of the file.
	Content(file string, cd ...ContentDisposition) error

	// Empty sends a response with no body.
	// You can use `Context.Status` to change status code (default is 200).
	Empty() error

	// Redirect redirects the request to a provided URL with status code.
	// You can use `Context.Status` to change status code.
	// If code wasn't set, default is 302 (http.StatusFound).
	Redirect(url string) error
}

Responser holds all methods for sending response.

type Router

type Router interface {
	Group(prefix string, filters ...Filter) *Group
	Use(filters ...Filter)

	Get(path string, h HandlerFunc, opts ...HandlerOption)
	Post(path string, h HandlerFunc, opts ...HandlerOption)
	Delete(path string, h HandlerFunc, opts ...HandlerOption)
	Put(path string, h HandlerFunc, opts ...HandlerOption)
	Head(path string, h HandlerFunc, opts ...HandlerOption)
	Options(path string, h HandlerFunc, opts ...HandlerOption)
	Patch(path string, h HandlerFunc, opts ...HandlerOption)
	Trace(path string, h HandlerFunc, opts ...HandlerOption)
	Connect(path string, h HandlerFunc, opts ...HandlerOption)
	Any(path string, handler HandlerFunc, opts ...HandlerOption)
	Match(methods []string, path string, h HandlerFunc, opts ...HandlerOption)
	Handle(path string, controller interface{}, filters ...Filter)

	Static(prefix string, fs http.FileSystem, fallback string, filters ...Filter)
	File(path string, fs http.FileSystem, name string, filters ...Filter)
}

type Server

type Server struct {
	ErrorHandler ErrorHandler
	Binder       Binder
	Validator    Validator
	Renderer     Renderer
	Logger       log.Logger
	// contains filtered or unexported fields
}

Server represents information of the HTTP server.

func Auto

func Auto() (server *Server)

Auto creates an instance of Server with options loaded from app.yaml/app.toml.

func Default

func Default(address ...string) (server *Server)

Default creates an instance of Server with default options.

func New

func New(c *Options) (s *Server)

New creates an instance of Server.

func (*Server) AcquireContext

func (s *Server) AcquireContext(w http.ResponseWriter, r *http.Request) Context

AcquireContext returns an `Context` instance from the pool. You must return the context by calling `ReleaseContext()`.

func (*Server) Any

func (s *Server) Any(path string, handler HandlerFunc, opts ...HandlerOption)

Any registers a route that matches all the HTTP methods.

func (*Server) Close

func (s *Server) Close(timeout time.Duration)

Close gracefully shutdown the internal HTTP servers with timeout.

func (*Server) Connect

func (s *Server) Connect(path string, h HandlerFunc, opts ...HandlerOption)

Connect registers a route that matches 'CONNECT' method.

func (*Server) Delete

func (s *Server) Delete(path string, h HandlerFunc, opts ...HandlerOption)

Delete registers a route that matches 'DELETE' method.

func (*Server) File

func (s *Server) File(path string, fs http.FileSystem, name string, filters ...Filter)

File registers a route in order to server a single file of filesystem.

func (*Server) Get

func (s *Server) Get(path string, h HandlerFunc, opts ...HandlerOption)

Get registers a route that matches 'GET' method.

func (*Server) Group

func (s *Server) Group(prefix string, filters ...Filter) (g *Group)

Group creates a new router group.

func (*Server) Handle

func (s *Server) Handle(path string, controller interface{}, filters ...Filter)

Handle registers routes from controller. It panics if controller's Kind is not struct.

func (*Server) Handler

func (s *Server) Handler(name string) (handler HandlerInfo)

func (*Server) Head

func (s *Server) Head(path string, h HandlerFunc, opts ...HandlerOption)

Head registers a route that matches 'HEAD' method.

func (*Server) Match

func (s *Server) Match(methods []string, path string, handler HandlerFunc, opts ...HandlerOption)

Match registers a route that matches specific methods.

func (*Server) Options

func (s *Server) Options(path string, h HandlerFunc, opts ...HandlerOption)

Options registers a route that matches 'OPTIONS' method.

func (*Server) Patch

func (s *Server) Patch(path string, h HandlerFunc, opts ...HandlerOption)

Patch registers a route that matches 'PATCH' method.

func (*Server) Post

func (s *Server) Post(path string, h HandlerFunc, opts ...HandlerOption)

Post registers a route that matches 'POST' method.

func (*Server) Put

func (s *Server) Put(path string, h HandlerFunc, opts ...HandlerOption)

Put registers a route that matches 'PUT' method.

func (*Server) ReleaseContext

func (s *Server) ReleaseContext(c Context)

ReleaseContext returns the `Context` instance back to the pool.

func (*Server) Router

func (s *Server) Router() *router.Tree

Router returns router.

func (*Server) Serve

func (s *Server) Serve() error

Serve starts the HTTP server.

func (*Server) ServeHTTP

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

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

func (*Server) Static

func (s *Server) Static(prefix string, sys http.FileSystem, fallback string, filters ...Filter)

Static serves static files from a custom file system.

func (*Server) Trace

func (s *Server) Trace(path string, h HandlerFunc, opts ...HandlerOption)

Trace registers a route that matches 'TRACE' method.

func (*Server) URL

func (s *Server) URL(name string, params ...interface{}) string

URL generates an URL from handler name and provided parameters.

func (*Server) Use

func (s *Server) Use(filters ...Filter)

Use adds global filters to the router.

func (*Server) UseFunc

func (s *Server) UseFunc(filters ...FilterFunc)

UseFunc adds global filters to the router.

type Unmarshaler

type Unmarshaler interface {
	// Unmarshal converts a param value to type.
	Unmarshal(param interface{}) error
}

Unmarshaler is the interface implemented by types that can unmarshal a param to themselves.

type User

type User = security.User

type Validator

type Validator interface {
	Validate(i interface{}) error
}

Validator is the interface that check data is valid or not.

Directories

Path Synopsis
jet
std

Jump to

Keyboard shortcuts

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