http

package module
v1.0.10 Latest Latest
Warning

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

Go to latest
Published: May 21, 2022 License: MIT Imports: 29 Imported by: 1

README

http

Documentation

Index

Constants

View Source
const (
	SameSiteDefaultMode = http.SameSiteDefaultMode
	SameSiteLaxMode     = http.SameSiteLaxMode
	SameSiteStrictMode  = http.SameSiteStrictMode
	SameSiteNoneMode    = http.SameSiteNoneMode
)
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"

	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"
)

Header types

View Source
const (
	MimeApplicationJSON       = "application/json; " + charsetUTF8
	MimeApplicationJavaScript = "application/javascript; " + charsetUTF8
	MimeApplicationXML        = "application/xml; " + charsetUTF8
	MimeTextXML               = "text/xml; " + charsetUTF8
	MimeApplicationForm       = "application/x-www-form-urlencoded"
	MimeApplicationProtobuf   = "application/protobuf"
	MimeApplicationMsgpack    = "application/msgpack"
	MimeTextHTML              = "text/html; " + charsetUTF8
	MimeTextPlain             = "text/plain; " + charsetUTF8
	MimeMultipartForm         = "multipart/form-data"
	MimeOctetStream           = "application/octet-stream"
)

Mime types

View Source
const (
	MethodGet     = "GET"
	MethodHead    = "HEAD"
	MethodPost    = "POST"
	MethodPut     = "PUT"
	MethodPatch   = "PATCH" // RFC 5789
	MethodDelete  = "DELETE"
	MethodConnect = "CONNECT"
	MethodOptions = "OPTIONS"
	MethodTrace   = "TRACE"
)

common http methods

View Source
const (
	StatusContinue           = 100 // RFC 7231, 6.2.1
	StatusSwitchingProtocols = 101 // RFC 7231, 6.2.2
	StatusProcessing         = 102 // RFC 2518, 10.1
	StatusEarlyHints         = 103 // RFC 8297

	StatusOK                   = 200 // RFC 7231, 6.3.1
	StatusCreated              = 201 // RFC 7231, 6.3.2
	StatusAccepted             = 202 // RFC 7231, 6.3.3
	StatusNonAuthoritativeInfo = 203 // RFC 7231, 6.3.4
	StatusNoContent            = 204 // RFC 7231, 6.3.5
	StatusResetContent         = 205 // RFC 7231, 6.3.6
	StatusPartialContent       = 206 // RFC 7233, 4.1
	StatusMultiStatus          = 207 // RFC 4918, 11.1
	StatusAlreadyReported      = 208 // RFC 5842, 7.1
	StatusIMUsed               = 226 // RFC 3229, 10.4.1

	StatusMultipleChoices  = 300 // RFC 7231, 6.4.1
	StatusMovedPermanently = 301 // RFC 7231, 6.4.2
	StatusFound            = 302 // RFC 7231, 6.4.3
	StatusSeeOther         = 303 // RFC 7231, 6.4.4
	StatusNotModified      = 304 // RFC 7232, 4.1
	StatusUseProxy         = 305 // RFC 7231, 6.4.5

	StatusTemporaryRedirect = 307 // RFC 7231, 6.4.7
	StatusPermanentRedirect = 308 // RFC 7538, 3

	StatusBadRequest                   = 400 // RFC 7231, 6.5.1
	StatusUnauthorized                 = 401 // RFC 7235, 3.1
	StatusPaymentRequired              = 402 // RFC 7231, 6.5.2
	StatusForbidden                    = 403 // RFC 7231, 6.5.3
	StatusNotFound                     = 404 // RFC 7231, 6.5.4
	StatusMethodNotAllowed             = 405 // RFC 7231, 6.5.5
	StatusNotAcceptable                = 406 // RFC 7231, 6.5.6
	StatusProxyAuthRequired            = 407 // RFC 7235, 3.2
	StatusRequestTimeout               = 408 // RFC 7231, 6.5.7
	StatusConflict                     = 409 // RFC 7231, 6.5.8
	StatusGone                         = 410 // RFC 7231, 6.5.9
	StatusLengthRequired               = 411 // RFC 7231, 6.5.10
	StatusPreconditionFailed           = 412 // RFC 7232, 4.2
	StatusRequestEntityTooLarge        = 413 // RFC 7231, 6.5.11
	StatusRequestURITooLong            = 414 // RFC 7231, 6.5.12
	StatusUnsupportedMediaType         = 415 // RFC 7231, 6.5.13
	StatusRequestedRangeNotSatisfiable = 416 // RFC 7233, 4.4
	StatusExpectationFailed            = 417 // RFC 7231, 6.5.14
	StatusTeapot                       = 418 // RFC 7168, 2.3.3
	StatusMisdirectedRequest           = 421 // RFC 7540, 9.1.2
	StatusUnprocessableEntity          = 422 // RFC 4918, 11.2
	StatusLocked                       = 423 // RFC 4918, 11.3
	StatusFailedDependency             = 424 // RFC 4918, 11.4
	StatusTooEarly                     = 425 // RFC 8470, 5.2.
	StatusUpgradeRequired              = 426 // RFC 7231, 6.5.15
	StatusPreconditionRequired         = 428 // RFC 6585, 3
	StatusTooManyRequests              = 429 // RFC 6585, 4
	StatusRequestHeaderFieldsTooLarge  = 431 // RFC 6585, 5
	StatusUnavailableForLegalReasons   = 451 // RFC 7725, 3

	StatusInternalServerError           = 500 // RFC 7231, 6.6.1
	StatusNotImplemented                = 501 // RFC 7231, 6.6.2
	StatusBadGateway                    = 502 // RFC 7231, 6.6.3
	StatusServiceUnavailable            = 503 // RFC 7231, 6.6.4
	StatusGatewayTimeout                = 504 // RFC 7231, 6.6.5
	StatusHTTPVersionNotSupported       = 505 // RFC 7231, 6.6.6
	StatusVariantAlsoNegotiates         = 506 // RFC 2295, 8.1
	StatusInsufficientStorage           = 507 // RFC 4918, 11.5
	StatusLoopDetected                  = 508 // RFC 5842, 7.2
	StatusNotExtended                   = 510 // RFC 2774, 7
	StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6
)

Variables

View Source
var (
	// ErrMessageTooLarge is returned by ReadForm if the message form
	// data is too large to be processed.
	ErrMessageTooLarge = multipart.ErrMessageTooLarge

	// ErrNoCookie is returned by Request's Cookie method when a cookie is not found.
	ErrNoCookie = http.ErrNoCookie

	// ErrMissingFile is returned by FormFile when the provided file field name
	// is either not present in the request or not a file field.
	ErrMissingFile = http.ErrMissingFile
)
View Source
var DefaultNotFound = func(r *Request) error {
	return r.Response.StatusNotFound()
}

Functions

func PutFormReader

func PutFormReader(fr *FormReader)

PutFormReader to pool

func PutRequest

func PutRequest(r *Request)

PutRequest to pool

func StatusBytes

func StatusBytes(code int) []byte

StatusBytes returns a text bytes for the HTTP status code. It returns the empty string if the code is unknown.

func StatusText

func StatusText(code int) string

StatusText returns a text for the HTTP status code. It returns the empty string if the code is unknown.

Types

type Compressor

type Compressor struct {
	MinSize int // default: 0 bytes
	MaxSize int // default: unlimit

	GzipDisable   bool
	GzipMinFactor float64 // default: 0.75 from origin size
	GzipLevel     int     // range [0,9], default: 9

	BrotliDisable   bool
	BrotliMinFactor float64 // default: 0.75 from origin size
	BrotliLevel     int     // range [0,11], default: 6
	// contains filtered or unexported fields
}

Compressor config for static route

func (*Compressor) ApplyBrotli

func (c *Compressor) ApplyBrotli(w io.Writer, data []byte) error

ApplyBrotli compress

func (*Compressor) ApplyGzip

func (c *Compressor) ApplyGzip(w io.Writer, data []byte) error

ApplyGzip compress

func (*Compressor) Init

func (c *Compressor) Init() error

Init compressor

func (*Compressor) ValidSize

func (c *Compressor) ValidSize(size int) bool

ValidSize by config

type Cookie = http.Cookie

A Cookie represents an HTTP cookie as sent in the Set-Cookie header of an HTTP response or the Cookie header of an HTTP request.

See https://tools.ietf.org/html/rfc6265 for details.

type FormReader

type FormReader struct {
	IsFile      bool
	Name        string
	Filename    string
	ContentType string
	// contains filtered or unexported fields
}

FormReader for multipart fields

func GetFormReader

func GetFormReader(req *http.Request) *FormReader

GetFormReader from pool and fill

func NewFormReader

func NewFormReader(r *http.Request) *FormReader

NewFormReader for multipart fields

func (*FormReader) NextField

func (r *FormReader) NextField() bool

NextField parsed field header if available

func (*FormReader) Read

func (r *FormReader) Read(b []byte) (n int, _ error)

func (*FormReader) ReadBytes

func (r *FormReader) ReadBytes() ([]byte, error)

ReadBytes of field value

func (*FormReader) ReadString

func (r *FormReader) ReadString() string

ReadString of field value

func (*FormReader) Remaining

func (r *FormReader) Remaining() int64

Remaining bytes count

func (*FormReader) Reset

func (r *FormReader) Reset(req *http.Request)

Reset request form

func (*FormReader) Skip

func (r *FormReader) Skip() (n int64)

Skip field data

type Handler

type Handler func(*Request) error

func WrapHandler

func WrapHandler(h http.Handler) Handler

func WrapHandlerFunc

func WrapHandlerFunc(f http.HandlerFunc) Handler
type Header = http.Header

A Header represents the key-value pairs in an HTTP header.

The keys should be in canonical form, as returned by CanonicalHeaderKey.

type Middleware

type Middleware interface {
	Handler(next Handler) Handler
}

type MiddlewareFunc

type MiddlewareFunc func(next Handler) Handler

func (MiddlewareFunc) Handler

func (f MiddlewareFunc) Handler(next Handler) Handler

type NewRoutesCallback

type NewRoutesCallback func(method, path string)

type Request

type Request struct {
	*http.Request
	context.Context

	Response *Response

	Payload interface{}

	RouteVals []RouteValue
	RouteTail string
	RoutePath string
	// contains filtered or unexported fields
}

Request net/http with context.Context, current route and ResponseWriter

func GetRequest

func GetRequest(w http.ResponseWriter, r *http.Request) *Request

GetRequest from pool and fill

func (*Request) FormFile

func (r *Request) FormFile(key string) *multipart.FileHeader

FormFile without opening or nil if not found

func (*Request) FormFileData

func (r *Request) FormFileData(key string) ([]byte, *multipart.FileHeader)

FormFileData and header

func (*Request) FormFiles

func (r *Request) FormFiles(key string) []*multipart.FileHeader

FormFiles without opening or nil if not found

func (*Request) FormReader

func (r *Request) FormReader() *FormReader

FormReader requence

func (*Request) ParseJSON

func (r *Request) ParseJSON(dst interface{}) error

ParseJSON via easyjson or standard decoder

func (*Request) RealIP

func (r *Request) RealIP() string

RealIP of request headers

func (*Request) RouteInt

func (r *Request) RouteInt(name string) int64

RouteInt value

func (*Request) RouteStr

func (r *Request) RouteStr(name string) string

RouteStr value

func (*Request) URI

func (r *Request) URI() string

URI of request with query

func (*Request) UserAgent

func (r *Request) UserAgent() *user_agent.UserAgent

UserAgent parse via github.com/mssola/user_agent

type Response

type Response struct {
	http.ResponseWriter
	// contains filtered or unexported fields
}

func (*Response) Bytes

func (r *Response) Bytes(status int, b []byte) (err error)

func (*Response) Flush added in v1.0.7

func (r *Response) Flush()

Flush implements the http.Flusher interface to allow an HTTP handler to flush buffered data to the client

func (*Response) HTMLBytes

func (r *Response) HTMLBytes(code int, html []byte) error

func (*Response) HTMLString

func (r *Response) HTMLString(code int, html string) error

func (*Response) HTMLTemplate

func (r *Response) HTMLTemplate(code int, tmpl *htemplate.Template, data interface{}) error

func (*Response) Hijack added in v1.0.7

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

func (*Response) Int

func (r *Response) Int(status int, v int) error

func (*Response) Int64

func (r *Response) Int64(status int, v int64) error

func (*Response) JSON

func (r *Response) JSON(status int, src interface{}) error

func (*Response) Redirect

func (r *Response) Redirect(toURL string) error

func (*Response) RedirectPermanent

func (r *Response) RedirectPermanent(toURL string) error

func (*Response) ResponseCode

func (r *Response) ResponseCode() int

func (*Response) ResponseSize

func (r *Response) ResponseSize() int

func (*Response) SetCookie

func (r *Response) SetCookie(cookie *Cookie)

func (*Response) Status

func (r *Response) Status(code int) error

func (*Response) StatusBadRequest added in v1.0.2

func (r *Response) StatusBadRequest() error

func (*Response) StatusConflict added in v1.0.2

func (r *Response) StatusConflict() error

func (*Response) StatusCreated added in v1.0.2

func (r *Response) StatusCreated() error

func (*Response) StatusForbidden added in v1.0.2

func (r *Response) StatusForbidden() error

func (*Response) StatusNoContent added in v1.0.2

func (r *Response) StatusNoContent() error

func (*Response) StatusNotFound added in v1.0.2

func (r *Response) StatusNotFound() error

func (*Response) StatusOK added in v1.0.2

func (r *Response) StatusOK() error

func (*Response) StatusTooLarge added in v1.0.2

func (r *Response) StatusTooLarge() error

func (*Response) StatusUnauthorized added in v1.0.2

func (r *Response) StatusUnauthorized() error

func (*Response) String

func (r *Response) String(status int, s string) error

func (*Response) TextTemplate

func (r *Response) TextTemplate(code int, tmpl *ttemplate.Template, data interface{}) error

func (*Response) Write

func (r *Response) Write(data []byte) (int, error)

func (*Response) WriteHeader

func (r *Response) WriteHeader(statusCode int)

type ResponseWriter

type ResponseWriter = http.ResponseWriter

A ResponseWriter interface is used by an HTTP handler to construct an HTTP response.

A ResponseWriter may not be used after the Handler.ServeHTTP method has returned.

type RouteValue

type RouteValue struct {
	Raw string
	Int int64
	// contains filtered or unexported fields
}

RouteValue of web.Router handler

type Router

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

Router with handlers and middlewares

func NewRouter

func NewRouter() *Router

func (*Router) AddMiddleware

func (r *Router) AddMiddleware(middlewares ...Middleware)

AddMiddleware for the next handlers

func (*Router) CONNECT

func (r *Router) CONNECT(path string, h Handler, m ...Middleware)

CONNECT is alias ROUTE with method Connect

func (*Router) DELETE

func (r *Router) DELETE(path string, h Handler, m ...Middleware)

DELETE is alias ROUTE with method Delete

func (*Router) File

func (r *Router) File(routePath, filename string)

File serve

func (*Router) Fork

func (r *Router) Fork(path string) *Router

Fork router by path

func (*Router) GET

func (r *Router) GET(path string, h Handler, m ...Middleware)

GET is alias ROUTE with method Get

func (*Router) Group

func (r *Router) Group(path string, subRoutes func())

Group routes by path

func (*Router) HEAD

func (r *Router) HEAD(path string, h Handler, m ...Middleware)

HEAD is alias ROUTE with method Head

func (*Router) Media

func (r *Router) Media(routePath, rootDir string)

Media fileserver

func (*Router) NotFound

func (r *Router) NotFound(h Handler)

NotFound set

func (*Router) OPTIONS

func (r *Router) OPTIONS(path string, h Handler, m ...Middleware)

OPTIONS is alias ROUTE with method Options

func (*Router) PATCH

func (r *Router) PATCH(path string, h Handler, m ...Middleware)

PATCH is alias ROUTE with method Patch

func (*Router) POST

func (r *Router) POST(path string, h Handler, m ...Middleware)

POST is alias ROUTE with method Post

func (*Router) PUT

func (r *Router) PUT(path string, h Handler, m ...Middleware)

PUT is alias ROUTE with method Put

func (*Router) ROUTE

func (r *Router) ROUTE(method, path string, h Handler, m ...Middleware)

ROUTE is add handler to router with http method

func (*Router) Redirect

func (r *Router) Redirect(path, method, toURL string, permanent bool)

Redirect request

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(originWriter http.ResponseWriter, originRequest *http.Request)

func (*Router) Static

func (r *Router) Static(routePath, rootDir string, compress *Compressor) error

Static cached fileserver, compress if set

func (*Router) StaticFS

func (r *Router) StaticFS(routePath, rootDir string, fsDir *embed.FS, compress *Compressor) error

StaticFS cached fileserver, compress if set

func (*Router) StaticFile

func (r *Router) StaticFile(routePath, filename string, compress *Compressor) error

StaticFile serve, compress if set

func (*Router) StaticFileFS

func (r *Router) StaticFileFS(routePath, filename string, fs *embed.FS, compress *Compressor) error

StaticFileFS serve, compress if set

func (*Router) TRACE

func (r *Router) TRACE(path string, h Handler, m ...Middleware)

TRACE is alias ROUTE with method Trace

func (*Router) WithLogNewRoutes

func (r *Router) WithLogNewRoutes(f NewRoutesCallback) *Router

type SameSite

type SameSite = http.SameSite

SameSite allows a server to define a cookie attribute making it impossible for the browser to send this cookie along with cross-site requests. The main goal is to mitigate the risk of cross-origin information leakage, and provide some protection against cross-site request forgery attacks.

See https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00 for details.

type Server

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

func NewServer

func NewServer() *Server

func (*Server) Close

func (s *Server) Close() error

func (*Server) Start

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

func (*Server) WithErrorLog

func (s *Server) WithErrorLog(logger *log.Logger) *Server

func (*Server) WithHandler

func (s *Server) WithHandler(h http.Handler) *Server

func (*Server) WithHost

func (s *Server) WithHost(listenHost string) *Server

func (*Server) WithPort

func (s *Server) WithPort(listenPort uint16) *Server

func (*Server) WithTimeouts

func (s *Server) WithTimeouts(readTimeout, writeTimeout, idleTimeout time.Duration) *Server

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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