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 Debug(prefix string) (string, http.Handler)deprecated
- 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 Group(prefix string, fn func() http.Handler) (string, http.Handler)
- 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
- type ParamLocation
- type Router
- func (r *Router) Group(prefix string, fn func(*Router))
- func (r *Router) Handle(pattern string, handler http.Handler)
- func (r *Router) HandleFunc(pattern string, handler http.HandlerFunc)
- 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 ¶
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 ¶
Example ¶
package main
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"github.com/infastin/gorack/opt"
"github.com/infastin/gorack/xrest"
)
func main() {
mux := http.NewServeMux()
type Inline struct {
A string `query:"a"`
B string `query:"b"`
}
type Params struct {
Inline `inline:""`
Foo int `query:"foo"`
NullableFoo opt.NullInt[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 := xrest.BindParams(r, ¶ms); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
xrest.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"},
"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","Foo":42,"NullableFoo":null,"Bar":123,"Baz":"qux"}
func Blob ¶
func Blob(w http.ResponseWriter, code int, data []byte)
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 ¶
Adds the given prefix to the documentation handler and returns pattern and http handler for (*http.ServeMux).Handle-like methods.
func DocumentationHandler ¶ added in v1.1.0
Returns http handler that provides OpenAPI specification page. Uses Stoplight Elements.
func 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 Group ¶
Adds the given prefix to the http handler returned from fn and returns pattern and http handler for (*http.ServeMux).Handle-like methods.
func HTML ¶
func HTML(w http.ResponseWriter, code int, body []byte)
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)
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)
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)
Writes http headers with the given status code.
func Prefix ¶ added in v1.1.0
Adds the given prefix to the given http handler and returns pattern and http handler for (*http.ServeMux).Handle-like methods.
func Profiler ¶ added in v1.1.0
Adds the given prefix to the profiler handler and returns pattern and http handler for (*http.ServeMux).Handle-like methods.
func ProfilerHandler ¶ added in v1.1.0
Returns http handler that provides /pprof routes.
func Stream ¶
func Stream(w http.ResponseWriter, code int, content io.Reader)
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)
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)
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)
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)
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 Chain ¶
func Chain(middlewares ...Middleware) Middleware
func Context ¶
func Context() Middleware
func MethodNotAllowed ¶
func MethodNotAllowed(handler http.HandlerFunc) Middleware
Middleware that allows to catch http.StatusMethodNotAllowed codes written to http.ResponseWriter and handle them.
func NotFound ¶
func NotFound(handler http.HandlerFunc) Middleware
Middleware that allows to catch http.StatusNotFound codes written to http.ResponseWriter and handle them.
func Timeout ¶ added in v1.1.0
func Timeout(timeout time.Duration) Middleware
func TimeoutCause ¶ added in v1.1.0
func TimeoutCause(timeout time.Duration, cause error) Middleware
type ParamLocation ¶
type ParamLocation string
const ( ParamLocationQuery ParamLocation = "query" ParamLocationHeader ParamLocation = "header" ParamLocationPath ParamLocation = "path" ParamLocationInline ParamLocation = "inline" )
type Router ¶ added in v1.1.0
type Router struct {
// contains filtered or unexported fields
}
func (*Router) HandleFunc ¶ added in v1.1.0
func (r *Router) HandleFunc(pattern string, handler http.HandlerFunc)
func (*Router) ServeHTTP ¶ added in v1.1.0
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)
func (*Router) Use ¶ added in v1.1.0
func (r *Router) Use(middlewares ...Middleware)