Documentation
¶
Index ¶
- func Attachment(w http.ResponseWriter, code int, filename string, content io.Reader, ...)
- func BindParams(r *http.Request, output any) error
- func Blob(w http.ResponseWriter, code int, data []byte)
- func Documentation(name, basePath, prefix string, spec []byte) (string, http.Handler)
- func DocumentationHandler(name, basePath string, spec []byte) http.Handler
- func Error(r *http.Request, err error)
- func File(w http.ResponseWriter, code int, filename string, content io.Reader, ...)
- func Get[T any](r *http.Request, key string) (val T, ok bool)
- func GetError(r *http.Request) error
- func HTML(w http.ResponseWriter, code int, body []byte)
- func HTMLTemplate(w http.ResponseWriter, code int, tmpl *htmltemplate.Template, data any)
- func JSON(w http.ResponseWriter, code int, body any)
- func NoContent(w http.ResponseWriter, code int)
- func Prefix(prefix string, handler http.Handler) (string, http.Handler)
- func Profiler(prefix string) (string, http.Handler)
- func ProfilerHandler() http.Handler
- func RealIP(r *http.Request) net.IP
- func Set[T any](r *http.Request, key string, value T)
- func Stream(w http.ResponseWriter, code int, content io.Reader)
- func Text(w http.ResponseWriter, code int, body []byte)
- func TextTemplate(w http.ResponseWriter, code int, tmpl *texttemplate.Template, data any)
- func XML(w http.ResponseWriter, code int, body any)
- func XMLWithHeader(w http.ResponseWriter, code int, body any)
- type BindParamsTypeError
- type BindParamsValueError
- type InvalidBindParamsError
- type Middleware
- func CatchStatus(code int, handler http.HandlerFunc) Middleware
- func Chain(middlewares ...Middleware) Middleware
- func Context() Middleware
- func MethodNotAllowed(handler http.HandlerFunc) Middleware
- func NotFound(handler http.HandlerFunc) Middleware
- func RemoveStatusCatchers(handler http.HandlerFunc) Middleware
- func Timeout(timeout time.Duration) Middleware
- func TimeoutCause(timeout time.Duration, cause error) Middleware
- type ParamLocation
- type Router
- func (r *Router) Group(prefix string, fn func(group *Router))
- func (r *Router) Handle(pattern string, handler http.Handler)
- func (r *Router) HandleFunc(pattern string, handler http.HandlerFunc)
- func (r *Router) Mount(prefix string, handler http.Handler)
- func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)
- func (r *Router) Use(middlewares ...Middleware)
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Attachment ¶
Attachment writes content as an attachment with the given filename and with the given status code. If size is not zero, sets Content-Length. If Content-Type is not set, tries to determine it from the extension of filename and content itself, falling back to "application/octet-stream" if it is unable to determine a valid MIME type, and sets Content-Type to the resulting MIME type. NOTE: It is recommended to use http.ServeContent instead of this function.
func BindParams ¶
BindParams decodes request parameters (query, header, path) into a struct using struct tags.
Example ¶
package main
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"github.com/infastin/gorack/xhttp"
)
func main() {
mux := http.NewServeMux()
type Anonymous struct {
A string `query:"a"`
B string `query:"b"`
}
type Inline struct {
C string `query:"c"`
D string `query:"d"`
}
type Params struct {
Anonymous
Inline Inline `inline:""`
Foo int `query:"foo"`
NullableFoo *int `query:"nullable_foo"`
Bar int `header:"bar"`
Baz string `path:"baz"`
}
mux.HandleFunc("GET /params/{baz}", func(w http.ResponseWriter, r *http.Request) {
var params Params
if err := xhttp.BindParams(r, ¶ms); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
xhttp.JSON(w, http.StatusOK, ¶ms)
})
ts := httptest.NewServer(mux)
defer ts.Close()
uri, _ := url.Parse(ts.URL)
query := url.Values{
"a": []string{"I am A"},
"b": []string{"Hello from B"},
"c": []string{"Hello from C"},
"d": []string{"I am D"},
"foo": []string{"42"},
}
uri.Path = "/params/qux"
uri.RawQuery = query.Encode()
resp, err := ts.Client().Do(&http.Request{
Method: http.MethodGet,
URL: uri,
Header: http.Header{"bar": []string{"123"}},
})
if err != nil {
panic(err)
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
panic(err)
}
fmt.Printf("%s\n", data)
}
Output: {"A":"I am A","B":"Hello from B","Inline":{"C":"Hello from C","D":"I am D"},"Foo":42,"NullableFoo":null,"Bar":123,"Baz":"qux"}
func Blob ¶
func Blob(w http.ResponseWriter, code int, data []byte)
Blob writes data with the given status code. and Content-Type set to "application/octet-stream". Also sets Content-Length to the length of data.
func Documentation ¶
Documentation adds the given prefix to the documentation handler and returns pattern and http handler for (*http.ServeMux).Handle-like methods.
func DocumentationHandler ¶
DocumentationHandler returns http handler that provides OpenAPI specification page. Uses Stoplight Elements.
func File ¶
File writes content as is with the given status code. If size is not zero, sets Content-Length. If Content-Type is not set, tries to determine it from the extension of filename and content itself, falling back to "application/octet-stream" if it is unable to determine a valid MIME type, and sets Content-Type to the resulting MIME type. NOTE: It is recommended to use http.ServeContent instead of this function.
func HTML ¶
func HTML(w http.ResponseWriter, code int, body []byte)
HTML writes body with the given status code and Content-Type set to "text/html; charset=utf-8". Also sets Content-Length to the size of body.
func HTMLTemplate ¶
func HTMLTemplate(w http.ResponseWriter, code int, tmpl *htmltemplate.Template, data any)
HTMLTemplate executes html template tmpl with data and writes the output with the given status code and Content-Type set to "text/html; charset=utf-8".
func JSON ¶
func JSON(w http.ResponseWriter, code int, body any)
JSON encodes body as json and writes the output with the given status code and Content-Type set to "application/json".
func NoContent ¶
func NoContent(w http.ResponseWriter, code int)
NoContent writes http headers with the given status code.
func Prefix ¶
Prefix adds the given prefix to the given http handler and returns pattern and http handler for (*http.ServeMux).Handle-like methods.
func Profiler ¶
Profiler adds the given prefix to the profiler handler and returns pattern and http handler for (*http.ServeMux).Handle-like methods.
func ProfilerHandler ¶
ProfilerHandler returns http handler that provides /pprof routes.
func Set ¶
Set puts key-value pair in the context provided by Context middleware. NOTE: use Get to retrieve the value, using (context.Context).Value won't work.
func Stream ¶
func Stream(w http.ResponseWriter, code int, content io.Reader)
Stream writes content as is with the given status code. and Content-Type set to "application/octet-stream".
func Text ¶
func Text(w http.ResponseWriter, code int, body []byte)
Text writes body with the given status code and Content-Type set to "text/plain; charset=utf-8". Also sets Content-Length to the size of body.
func TextTemplate ¶
func TextTemplate(w http.ResponseWriter, code int, tmpl *texttemplate.Template, data any)
TextTemplate executes text template tmpl with data and writes the output with the given status code and Content-Type set to "text/plain; charset=utf-8".
func XML ¶
func XML(w http.ResponseWriter, code int, body any)
XML encodes body as xml and writes the output with the given status code and Content-Type set to "application/xml; charset=utf-8".
func XMLWithHeader ¶
func XMLWithHeader(w http.ResponseWriter, code int, body any)
XMLWithHeader encodes body as xml with <?xml> header and writes the output with the given status code and Content-Type set to "application/xml; charset=utf-8".
Types ¶
type BindParamsTypeError ¶
type BindParamsTypeError struct {
Location ParamLocation
Type reflect.Type
Struct string
Field string
}
func (*BindParamsTypeError) Error ¶
func (e *BindParamsTypeError) Error() string
type BindParamsValueError ¶
type BindParamsValueError struct {
Location ParamLocation
Name string
Value string
Err error
}
func (*BindParamsValueError) Error ¶
func (e *BindParamsValueError) Error() string
func (*BindParamsValueError) Unwrap ¶
func (e *BindParamsValueError) Unwrap() error
type InvalidBindParamsError ¶
type InvalidBindParamsError struct {
Location ParamLocation
Type reflect.Type
}
func (*InvalidBindParamsError) Error ¶
func (e *InvalidBindParamsError) Error() string
type Middleware ¶
func CatchStatus ¶ added in v1.6.0
func CatchStatus(code int, handler http.HandlerFunc) Middleware
CatchStatus is a middleware that allows to catch status codes written to http.ResponseWriter and handle them.
func Chain ¶
func Chain(middlewares ...Middleware) Middleware
Chain returns a new middleware that is the result of chaining multiple middlewares.
func Context ¶
func Context() Middleware
Context is a middleware that provides a custom context that can be used to set and get values and errors inside handlers and other middlewares.
func MethodNotAllowed ¶ added in v1.4.0
func MethodNotAllowed(handler http.HandlerFunc) Middleware
MethodNotAllowed is a middleware that allows to catch http.StatusMethodNotAllowed codes written to http.ResponseWriter and handle them.
func NotFound ¶ added in v1.4.0
func NotFound(handler http.HandlerFunc) Middleware
NotFound is a middleware that allows to catch http.StatusNotFound codes written to http.ResponseWriter and handle them.
func RemoveStatusCatchers ¶ added in v1.6.0
func RemoveStatusCatchers(handler http.HandlerFunc) Middleware
RemoveStatusCatchers is a middleware that removes wrappers around the original ResponseWriter that were added by NotFound, MethodNotAllowed and CatchStatus middlewares.
func Timeout ¶
func Timeout(timeout time.Duration) Middleware
Timeout is a middleware that will cancel request's context after the specified duration.
func TimeoutCause ¶
func TimeoutCause(timeout time.Duration, cause error) Middleware
TimeoutCause is a middleware that will cancel request's context with the given cause after the specified duration
type ParamLocation ¶
type ParamLocation string
const ( ParamLocationQuery ParamLocation = "query" ParamLocationHeader ParamLocation = "header" ParamLocationPath ParamLocation = "path" ParamLocationInline ParamLocation = "inline" )
type Router ¶ added in v1.4.0
type Router struct {
// contains filtered or unexported fields
}
Router is simple wrapper around http.ServerMux that introduces additional convenient methods.
func (*Router) HandleFunc ¶ added in v1.4.0
func (r *Router) HandleFunc(pattern string, handler http.HandlerFunc)
HandleFunc registers the handler function for the given pattern.
func (*Router) ServeHTTP ¶ added in v1.4.0
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)
ServeHTTP implements http.Handler interface, which serves HTTP requests.
func (*Router) Use ¶ added in v1.4.0
func (r *Router) Use(middlewares ...Middleware)
Use adds middlewares to the chain.