httputil

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Mar 1, 2023 License: MIT Imports: 8 Imported by: 1

README

httputil

helpers to create http rest services

features

  • bind json body
  • bind form body
  • bind xml body
  • bind query values
  • bind url.Values
  • custom error response writer
  • write json response
  • write xml response
  • write text response
  • write blob response
  • pprof handler and middleware

examples

  • example project

  • handler with json body

var ErrBadRequest = httputil.NewHTTPError(http.StatusBadRequest)

func CreateTaskHandler(svc TaskService) http.Handler {
 return httputil.NewHandler(func(w http.ResponseWriter, r *http.Request) error {
  var req CreateTaskRequest
  if err := httputil.BindJSON(r, &req); err != nil {
   return ErrBadRequest.WithCause(err)
  }

  res, err := svc.Create(r.Context(), req)
  if err != nil {
   return err
  }

  return httputil.WriteJSON(w, http.StatusCreated, res)
 })
}
  • handler with query params
func SearchTaskHandler(svc TaskService) http.Handler {
 return httputil.NewHandler(func(w http.ResponseWriter, r *http.Request) error {
  var req SearchTaskRequest
  if err := httputil.BindQuery(r, &req, httputil.WithTagName("json")); err != nil {
   return ErrBadRequest.WithCause(err)
  }

  res, err := svc.Search(r.Context(), req)
  if err != nil {
   return err
  }

  return httputil.WriteJSON(w, http.StatusOK, res)
 })
}
  • custom error encoder

func errorEncoder(w http.ResponseWriter, _ *http.Request, err error) {
 _ = httputil.WriteString(w, http.StatusInternalServerError, err.Error())
}

func CreateTaskHandler(svc TaskService) http.Handler {
 return httputil.NewHandler(func(w http.ResponseWriter, r *http.Request) error {
  // ...
 }).WithErrorEncoder(errorEncoder)
}

  • pprof handler
r := chi.NewRouter()
r.Handle("/debug/*", pprof.Handler())
  • pprof middleware
r := chi.NewRouter()
r.Use(pprof.Middleware)

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

	// Access 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"

	// Security
	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"
)
View Source
const (
	MimeApplicationJSON                  = "application/json"
	MimeApplicationJSONCharsetUTF8       = "application/json; charset=UTF-8"
	MimeApplicationJavaScript            = "application/javascript"
	MimeApplicationJavaScriptCharsetUTF8 = "application/javascript; charset=UTF-8"
	MimeApplicationXML                   = "application/xml"
	MimeApplicationXMLCharsetUTF8        = "application/xml; charset=UTF-8"
	MimeTextXML                          = "text/xml"
	MimeTextXMLCharsetUTF8               = "text/xml; charset=UTF-8"
	MimeApplicationForm                  = "application/x-www-form-urlencoded"
	MimeApplicationProtobuf              = "application/protobuf"
	MimeApplicationMsgpack               = "application/msgpack"
	MimeTextHTML                         = "text/html"
	MimeTextHTMLCharsetUTF8              = "text/html; charset=UTF-8"
	MimeTextPlain                        = "text/plain"
	MimeTextPlainCharsetUTF8             = "text/plain; charset=UTF-8"
	MimeMultipartForm                    = "multipart/form-data"
	MimeOctetStream                      = "application/octet-stream"
)
View Source
const (
	TagNameForm  = "form"
	TagNameQuery = "query"
	TagNameJSON  = "json"
)

Variables

View Source
var (
	ErrBadRequest                    = NewStatusError(http.StatusBadRequest)
	ErrUnauthorized                  = NewStatusError(http.StatusUnauthorized)
	ErrPaymentRequired               = NewStatusError(http.StatusPaymentRequired)
	ErrForbidden                     = NewStatusError(http.StatusForbidden)
	ErrNotFound                      = NewStatusError(http.StatusNotFound)
	ErrMethodNotAllowed              = NewStatusError(http.StatusMethodNotAllowed)
	ErrNotAcceptable                 = NewStatusError(http.StatusNotAcceptable)
	ErrProxyAuthRequired             = NewStatusError(http.StatusProxyAuthRequired)
	ErrRequestTimeout                = NewStatusError(http.StatusRequestTimeout)
	ErrConflict                      = NewStatusError(http.StatusConflict)
	ErrGone                          = NewStatusError(http.StatusGone)
	ErrLengthRequired                = NewStatusError(http.StatusLengthRequired)
	ErrPreconditionFailed            = NewStatusError(http.StatusPreconditionFailed)
	ErrRequestEntityTooLarge         = NewStatusError(http.StatusRequestEntityTooLarge)
	ErrRequestURITooLong             = NewStatusError(http.StatusRequestURITooLong)
	ErrUnsupportedMediaType          = NewStatusError(http.StatusUnsupportedMediaType)
	ErrRequestedRangeNotSatisfiable  = NewStatusError(http.StatusRequestedRangeNotSatisfiable)
	ErrExpectationFailed             = NewStatusError(http.StatusExpectationFailed)
	ErrTeapot                        = NewStatusError(http.StatusTeapot)
	ErrMisdirectedRequest            = NewStatusError(http.StatusMisdirectedRequest)
	ErrUnprocessableEntity           = NewStatusError(http.StatusUnprocessableEntity)
	ErrLocked                        = NewStatusError(http.StatusLocked)
	ErrFailedDependency              = NewStatusError(http.StatusFailedDependency)
	ErrTooEarly                      = NewStatusError(http.StatusTooEarly)
	ErrUpgradeRequired               = NewStatusError(http.StatusUpgradeRequired)
	ErrPreconditionRequired          = NewStatusError(http.StatusPreconditionRequired)
	ErrTooManyRequests               = NewStatusError(http.StatusTooManyRequests)
	ErrRequestHeaderFieldsTooLarge   = NewStatusError(http.StatusRequestHeaderFieldsTooLarge)
	ErrUnavailableForLegalReasons    = NewStatusError(http.StatusUnavailableForLegalReasons)
	ErrInternalServerError           = NewStatusError(http.StatusInternalServerError)
	ErrNotImplemented                = NewStatusError(http.StatusNotImplemented)
	ErrBadGateway                    = NewStatusError(http.StatusBadGateway)
	ErrServiceUnavailable            = NewStatusError(http.StatusServiceUnavailable)
	ErrGatewayTimeout                = NewStatusError(http.StatusGatewayTimeout)
	ErrHTTPVersionNotSupported       = NewStatusError(http.StatusHTTPVersionNotSupported)
	ErrVariantAlsoNegotiates         = NewStatusError(http.StatusVariantAlsoNegotiates)
	ErrInsufficientStorage           = NewStatusError(http.StatusInsufficientStorage)
	ErrLoopDetected                  = NewStatusError(http.StatusLoopDetected)
	ErrNotExtended                   = NewStatusError(http.StatusNotExtended)
	ErrNetworkAuthenticationRequired = NewStatusError(http.StatusNetworkAuthenticationRequired)
)

Functions

func BindForm

func BindForm(r *http.Request, v any, options ...FormOption) error

func BindJSON

func BindJSON(r *http.Request, v any) error

func BindQuery

func BindQuery(r *http.Request, v any, options ...FormOption) error

func BindValues

func BindValues(values url.Values, v any, options ...FormOption) error

func BindXML

func BindXML(r *http.Request, v any, options ...XMLOption) error

func WritXMLBlob

func WritXMLBlob(w http.ResponseWriter, code int, data []byte) error

func WriteBlob

func WriteBlob(w http.ResponseWriter, code int, contentType string, data []byte) error

func WriteJSON

func WriteJSON(w http.ResponseWriter, code int, v any) error

func WriteJSONBlob

func WriteJSONBlob(w http.ResponseWriter, code int, data []byte) error

func WriteNoContent

func WriteNoContent(w http.ResponseWriter, code int) error

func WriteStream

func WriteStream(w http.ResponseWriter, code int, contentType string, reader io.Reader) error

func WriteString

func WriteString(w http.ResponseWriter, code int, text string) error

func WriteXML

func WriteXML(w http.ResponseWriter, code int, v any) error

Types

type ErrorEncoderFunc

type ErrorEncoderFunc func(w http.ResponseWriter, r *http.Request, err error)

type FormOption

type FormOption func(*form.Decoder)

func WithTagName

func WithTagName(tagName string) FormOption

type HTTPError

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

func ErrorFrom

func ErrorFrom(err error) *HTTPError

func NewError added in v0.1.1

func NewError(code int, message string) *HTTPError

func NewStatusError added in v0.1.1

func NewStatusError(code int) *HTTPError

func (*HTTPError) Code

func (e *HTTPError) Code() int

func (*HTTPError) Error

func (e *HTTPError) Error() string

func (*HTTPError) Message

func (e *HTTPError) Message() string

func (*HTTPError) Unwrap

func (e *HTTPError) Unwrap() error

func (*HTTPError) WithCause

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

func (*HTTPError) WithMessage

func (e *HTTPError) WithMessage(m string) *HTTPError

type Handler

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

func NewHandler

func NewHandler(h HandlerFunc) *Handler

func (*Handler) ServeHTTP

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

func (*Handler) WithErrorEncoder

func (h *Handler) WithErrorEncoder(errorEncoder ErrorEncoderFunc) *Handler

func (*Handler) WithMiddlewares

func (h *Handler) WithMiddlewares(middlewares ...Middleware) *Handler

type HandlerFunc

type HandlerFunc func(w http.ResponseWriter, r *http.Request) error

type Middleware

type Middleware func(next HandlerFunc) HandlerFunc

type XMLOption

type XMLOption func(*xml.Decoder)

Directories

Path Synopsis
example module

Jump to

Keyboard shortcuts

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