http

package
v1.72.2 Latest Latest
Warning

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

Go to latest
Published: Apr 23, 2021 License: MIT Imports: 30 Imported by: 1

Documentation

Index

Constants

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
)
View Source
var DefaultNotFound = func(r *Request) error {
	return r.Response.StatusNotFound()
}

DefaultNotFound view for web.Router

View Source
var DefaultViewConverter = func(view interface{}) View {
	switch view := view.(type) {
	case func(*Request) error:
		return view
	case View:
		return view
	case Viewer:
		return view.View()
	case http.HandlerFunc:
		return func(r *Request) error {
			view(r.Response, r.Request)
			return nil
		}
	case http.Handler:
		return func(r *Request) error {
			view.ServeHTTP(r.Response, r.Request)
			return nil
		}
	case func(http.ResponseWriter, *http.Request):
		return func(r *Request) error {
			view(r.Response, r.Request)
			return nil
		}
	default:
		panic("wrong route view type")
	}
}

DefaultViewConverter for web.Router

Functions

func PutFormReader

func PutFormReader(fr *FormReader)

PutFormReader to pool

func PutRequest

func PutRequest(r *Request)

PutRequest to pool

func StartServer

func StartServer(conf ServerConfig, log zerolog.Logger, h http.Handler) (io.Closer, error)

StartServer http with config and logging

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 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 Middleware

type Middleware func(View) View

Middleware for web.Router handlers

type Middlewarer

type Middlewarer interface {
	View(View) View
}

Middlewarer is Middleware implementators

type Request

type Request struct {
	*http.Request
	context.Context

	Response *Response

	Log zerolog.Logger

	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(log zerolog.Logger, 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) Logger added in v1.72.2

func (r *Request) Logger() zerolog.Logger

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

type Response

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

Response writer

func (*Response) BadRequestJSON

func (r *Response) BadRequestJSON(src interface{}) error

BadRequestJSON is alias JSON with status BadRequest

func (*Response) BadRequestString

func (r *Response) BadRequestString(s string) error

BadRequestString is alias String with status BadRequest

func (*Response) Bytes

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

Bytes response with status code

func (*Response) CreatedInt

func (r *Response) CreatedInt(v int64) error

CreatedInt is alias Int with status Created

func (*Response) CreatedJSON

func (r *Response) CreatedJSON(src interface{}) error

CreatedJSON is alias JSON with status Created

func (*Response) CreatedString

func (r *Response) CreatedString(s string) error

CreatedString is alias String with status Created

func (*Response) HTMLBytes

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

HTMLBytes response

func (*Response) HTMLString

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

HTMLString response

func (*Response) HTMLTemplate

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

HTMLTemplate response

func (*Response) Int

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

Int response with status code

func (*Response) JSON

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

JSON response with status code

func (*Response) OKBytes

func (r *Response) OKBytes(b []byte) error

OKBytes is alias Bytes with status OK

func (*Response) OKInt

func (r *Response) OKInt(v int64) error

OKInt is alias Int with status OK

func (*Response) OKJSON

func (r *Response) OKJSON(src interface{}) error

OKJSON is alias JSON with status OK

func (*Response) OKString

func (r *Response) OKString(s string) error

OKString is alias String with status OK

func (*Response) Redirect

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

Redirect status code

func (*Response) RedirectPermanent

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

RedirectPermanent status code

func (*Response) SetCookie

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

SetCookie to response header

func (*Response) Status

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

Status response

func (*Response) StatusBadRequest

func (r *Response) StatusBadRequest() error

StatusBadRequest response

func (*Response) StatusCode

func (r *Response) StatusCode() int

StatusCode wrote

func (*Response) StatusCreated

func (r *Response) StatusCreated() error

StatusCreated response

func (*Response) StatusForbidden

func (r *Response) StatusForbidden() error

StatusForbidden response

func (*Response) StatusNoContent

func (r *Response) StatusNoContent() error

StatusNoContent response

func (*Response) StatusNotFound

func (r *Response) StatusNotFound() error

StatusNotFound response

func (*Response) StatusOK

func (r *Response) StatusOK() error

StatusOK response

func (*Response) StatusTooLarge

func (r *Response) StatusTooLarge() error

StatusTooLarge response

func (*Response) StatusUnauthorized

func (r *Response) StatusUnauthorized() error

StatusUnauthorized response

func (*Response) String

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

String response with status code

func (*Response) TextTemplate

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

TextTemplate response

func (*Response) Write

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

Write data

func (*Response) WriteHeader

func (r *Response) WriteHeader(statusCode int)

WriteHeader status code

type RouteValue

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

RouteValue of web.Router handler

type Router

type Router struct {
	ViewConverter func(interface{}) View
	OnAddRoute    func(method, path string)
	// contains filtered or unexported fields
}

Router http with web.View handlers and middlewares

func NewRouter

func NewRouter(log zerolog.Logger) *Router

NewRouter http

func (*Router) AddMiddleware

func (r *Router) AddMiddleware(middlewares ...interface{})

AddMiddleware to this router root

func (*Router) Connect

func (r *Router) Connect(path string, view interface{})

Connect is alias Route with method Connect

func (*Router) Delete

func (r *Router) Delete(path string, view interface{})

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, view interface{})

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, view interface{})

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(view interface{})

NotFound set

func (*Router) Options

func (r *Router) Options(path string, view interface{})

Options is alias Route with method Options

func (*Router) Patch

func (r *Router) Patch(path string, view interface{})

Patch is alias Route with method Patch

func (*Router) Post

func (r *Router) Post(path string, view interface{})

Post is alias Route with method Post

func (*Router) Put

func (r *Router) Put(path string, view interface{})

Put is alias Route with method Put

func (*Router) Redirect

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

Redirect request

func (*Router) Route

func (r *Router) Route(method, path string, view interface{})

Route is add view to router with http method

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, view interface{})

Trace is alias Route with method Trace

type ServerConfig

type ServerConfig struct {
	// Port for tcp socket
	Port uint16 `desc:"listen port for tcp socket"`
	Host string `desc:"listen address" default:"0.0.0.0"`

	TLS           bool `desc:"TLS enable. Using selfsigned certificate by empty cert/key"`
	TLSCertPath   string
	TLSKeyPath    string
	TLSSelfMaxAge time.Duration `default:"365d"`

	ReadTimeout  time.Duration `default:"20s"`
	WriteTimeout time.Duration `default:"30s"`
	IdleTimeout  time.Duration `default:"5s"`
}

ServerConfig http with options

func (*ServerConfig) ValidAndRepair

func (c *ServerConfig) ValidAndRepair() error

type View

type View func(*Request) error

View for web.Router

type Viewer

type Viewer interface {
	View() View
}

Viewer is View implementators

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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