httpx

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 4, 2022 License: MIT Imports: 15 Imported by: 0

README

httpx

A simple wrapper around net/http which makes HTTP handlers in Go more convenient to use.


httpx wraps http.Request into httpx.Request and defines a httpx.Responder that implements http.ResponseWriter to provide handy functions to send variety of HTTP responses.

The library also provides an idiomatic way to handle errors inside HTTP handlers by defining a httpx.HandlerFunc (which implements http.Handler) that has a better signature than http.HandlerFunc.

This is not a web framework, but rather an unopinionated library that extends net/http, as it does not include a HTTP router nor any mechanism that handles middlewares and the database layer.

In fact, you can leverage your favourite router e.g. gorilla/mux or chi to provide routing and middleware ability, and httpx works well with them.

Additionally, httpx.HandlerFunc is essentially a drop-in replacement for http.HandlerFunc. Most of the methods of httpx.Request and httpx.Responder are extracted from Echo's Context.

Consider this library as a lite version of Echo.

Why?

I want to use my favourite router along with some convenient methods from Echo's Context at the same time, but without other bloat and dependencies.

Roadmap

  • Request Data Binding
    • exposed a RequestBinder interface instead
  • Real IP Extractor
  • Graceful Shutdown
  • Better TLS Support

Credits

Most of the code is adapted and modified from labstack/echo, a high performance, minimalist web framework.


Made with ♥︎ by tnychn
MIT © 2022 Tony Chan

Documentation

Index

Constants

View Source
const (
	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"
)

MIME types

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"
	HeaderRetryAfter          = "Retry-After"
	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"
	HeaderXCorrelationID      = "X-Correlation-ID"
	HeaderXRequestedWith      = "X-Requested-With"
	HeaderServer              = "Server"
	HeaderOrigin              = "Origin"
	HeaderCacheControl        = "Cache-Control"
	HeaderConnection          = "Connection"

	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"
	HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only"
	HeaderXCSRFToken                      = "X-CSRF-Token"
	HeaderReferrerPolicy                  = "Referrer-Policy"
)

Headers

Variables

View Source
var (
	ErrUnsupportedMediaType        = NewHTTPError(http.StatusUnsupportedMediaType)
	ErrNotFound                    = NewHTTPError(http.StatusNotFound)
	ErrUnauthorized                = NewHTTPError(http.StatusUnauthorized)
	ErrForbidden                   = NewHTTPError(http.StatusForbidden)
	ErrMethodNotAllowed            = NewHTTPError(http.StatusMethodNotAllowed)
	ErrStatusRequestEntityTooLarge = NewHTTPError(http.StatusRequestEntityTooLarge)
	ErrTooManyRequests             = NewHTTPError(http.StatusTooManyRequests)
	ErrBadRequest                  = NewHTTPError(http.StatusBadRequest)
	ErrBadGateway                  = NewHTTPError(http.StatusBadGateway)
	ErrInternalServerError         = NewHTTPError(http.StatusInternalServerError)
	ErrRequestTimeout              = NewHTTPError(http.StatusRequestTimeout)
	ErrServiceUnavailable          = NewHTTPError(http.StatusServiceUnavailable)
)

HTTP Errors

View Source
var (
	// Logger is the global logger used to log library-specific internal errors.
	// Set this global variable to your preferred logger. Defaults to stdlib log.
	Logger logger = log.New(os.Stderr, "httpx: ", log.LstdFlags|log.Lmsgprefix)

	// HTTPErrorHandler is used to handle all HTTP errors returned by every HTTP handler.
	// Set this global variable to customise the behaviour.
	HTTPErrorHandler HTTPErrorHandlerFunc = HandleHTTPError(false)
)
View Source
var RequestBinder interface {
	Bind(req *Request, v any) error
}

RequestBinder is used to bind request body data to objects. Set this global variable to your preferred binder once before calling any Request.Bind. Defaults to nil.

Functions

This section is empty.

Types

type HTTPError

type HTTPError struct {
	Err     error
	Code    int
	Message string
}

HTTPError represents an error that occurred while handling a request.

func NewHTTPError

func NewHTTPError(code int, message ...string) *HTTPError

NewHTTPError creates a new HTTPError instance.

func WrapHTTPError

func WrapHTTPError(err error, code int, message ...string) *HTTPError

WrapHTTPError creates a new HTTPError instance with internal error set.

func (*HTTPError) Error

func (e *HTTPError) Error() string

Error makes it compatible with error interface.

func (*HTTPError) Unwrap

func (e *HTTPError) Unwrap() error

Unwrap satisfies the Go 1.13 error wrapper interface.

func (*HTTPError) WithError

func (e *HTTPError) WithError(err error) *HTTPError

WithError returns the same HTTPError instance with err set to HTTPError.err field

type HTTPErrorHandlerFunc

type HTTPErrorHandlerFunc func(req *Request, res *Responder, err error)

HTTPErrorHandlerFunc is a centralised handler for HTTPError.

func HandleHTTPError

func HandleHTTPError(expose bool) HTTPErrorHandlerFunc

HandleHTTPError returns the default HTTPErrorHandler used. If expose is true, returned response will be the internal error message.

type HandlerFunc

type HandlerFunc func(req *Request, res *Responder) error

HandlerFunc is an adapter to allow the use of ordinary functions as HTTP handlers, with *Request and *Responder as parameters.

If f is a function with the appropriate signature, HandlerFunc(f) is a http.Handler that calls f.

func H

func H(handler http.Handler) HandlerFunc

H is a convenient adapter that wraps the translation of http.Handler to HandlerFunc.

func (HandlerFunc) ServeHTTP

func (h HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP wraps http.Request into Request and http.ResponseWriter into Responder before passing them into and call h(req, res).

type Request

type Request struct {
	*http.Request // inherit from http.Request
	// contains filtered or unexported fields
}

Request wraps an *http.Request. See: https://golang.org/pkg/net/http/#Request

func NewRequest

func NewRequest(r *http.Request) *Request

NewRequest creates a new instance of Request.

func (*Request) Bind

func (r *Request) Bind(v any) error

Bind binds data from request body to v. Immediately panic if RequestBinder is not set in advance.

func (*Request) FormFile

func (r *Request) FormFile(name string) (*multipart.FileHeader, error)

FormFile returns the multipart form file for the provided name.

func (*Request) FormParams

func (r *Request) FormParams() (url.Values, error)

FormParams returns the form parameters as url.Values.

func (*Request) GetValue

func (r *Request) GetValue(key any) any

GetValue gets a value by key from the underlying http.Request's context.Context. The context can be retrieved using Request.Context().

func (*Request) IsTLS

func (r *Request) IsTLS() bool

IsTLS returns true if HTTP connection is TLS otherwise false.

func (*Request) IsWebSocket

func (r *Request) IsWebSocket() bool

IsWebSocket returns true if HTTP connection is WebSocket otherwise false.

func (*Request) MultipartForm

func (r *Request) MultipartForm() (*multipart.Form, error)

MultipartForm returns the multipart form.

func (*Request) QueryParam

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

QueryParam returns the query param for the provided name.

func (*Request) QueryParams

func (r *Request) QueryParams() url.Values

QueryParams returns the query parameters as url.Values.

func (*Request) QueryString

func (r *Request) QueryString() string

QueryString returns the URL query string.

func (*Request) Scheme

func (r *Request) Scheme() string

Scheme returns the HTTP protocol scheme, http or https.

func (*Request) SetValue

func (r *Request) SetValue(key, val any)

SetValue sets a value with key to the underlying http.Request's context.Context. The context can be retrieved using Request.Context().

type Responder

type Responder struct {
	Size       int64
	Committed  bool
	StatusCode int

	Writer http.ResponseWriter
	// contains filtered or unexported fields
}

Responder wraps an http.ResponseWriter and implements its interface to be used by an HTTP handler to construct an HTTP response. See: https://golang.org/pkg/net/http/#ResponseWriter

func NewResponder

func NewResponder(w http.ResponseWriter) *Responder

NewResponder creates a new instance of Responder.

func (*Responder) After

func (r *Responder) After(fn func())

After registers a function which is called just after the response is written. If the Content-Length is unknown, none of the after function is executed.

func (*Responder) Before

func (r *Responder) Before(fn func())

Before registers a function which is called just before the response is written.

func (*Responder) Blob

func (r *Responder) Blob(contentType string, b []byte) error

Blob sends a blob response with content type.

func (*Responder) Flush

func (r *Responder) 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 (*Responder) HTML

func (r *Responder) HTML(html string) error

HTML sends an HTTP response.

func (*Responder) Header

func (r *Responder) Header() http.Header

Header returns the header map for the writer that will be sent by WriteHeader. Changing the header after a call to WriteHeader (or Write) has no effect unless the modified headers were declared as trailers by setting the "Trailer" header before the call to WriteHeader (see example) To suppress implicit response headers, set their value to nil. Example: https://golang.org/pkg/net/http/#example_ResponseWriter_trailers

func (*Responder) Hijack

func (r *Responder) 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 (*Responder) JSON

func (r *Responder) JSON(i any, indent string) error

JSON sends a JSON response.

func (*Responder) NoContent

func (r *Responder) NoContent() error

NoContent sends a response with no body.

func (*Responder) Redirect

func (r *Responder) Redirect(url string) error

Redirect redirects the request to a provided URL.

func (*Responder) SetCookie

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

SetCookie adds a Set-Cookie header in HTTP response.

func (*Responder) Status

func (r *Responder) Status(code int) *Responder

Status sets the status code of the response without committing it.

func (*Responder) Stream

func (r *Responder) Stream(contentType string, reader io.Reader) error

Stream sends a streaming response with content type.

func (*Responder) String

func (r *Responder) String(s string) error

String sends a string response.

func (*Responder) Template

func (r *Responder) Template(tpl *template.Template, name string, data any) error

Template renders a template with data and sends a text/html response.

func (*Responder) Write

func (r *Responder) Write(b []byte) (n int, err error)

Write writes the data to the connection as part of an HTTP reply.

func (*Responder) WriteHeader

func (r *Responder) WriteHeader(code int)

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

func (*Responder) XML

func (r *Responder) XML(i any, indent string) error

XML sends an XML response.

Jump to

Keyboard shortcuts

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