xhttp

package module
v1.6.1 Latest Latest
Warning

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

Go to latest
Published: Jun 29, 2025 License: MIT Imports: 21 Imported by: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Attachment

func Attachment(w http.ResponseWriter, code int, filename string, content io.Reader, size int64)

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

func BindParams(r *http.Request, output any) error

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, &params); err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		xhttp.JSON(w, http.StatusOK, &params)
	})

	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

func Documentation(name, basePath, prefix string, spec []byte) (string, http.Handler)

Documentation adds the given prefix to the documentation handler and returns pattern and http handler for (*http.ServeMux).Handle-like methods.

func DocumentationHandler

func DocumentationHandler(name, basePath string, spec []byte) http.Handler

DocumentationHandler returns http handler that provides OpenAPI specification page. Uses Stoplight Elements.

func Error

func Error(r *http.Request, err error)

Error saves an error in the context provided by Context middleware.

func File

func File(w http.ResponseWriter, code int, filename string, content io.Reader, size int64)

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 Get

func Get[T any](r *http.Request, key string) (val T, ok bool)

Get looks up a key from the context provided by Context middleware.

func GetError

func GetError(r *http.Request) error

GetError returns an error saved in the context provided by Context middleware.

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

func Prefix(prefix string, handler http.Handler) (string, http.Handler)

Prefix adds the given prefix to the given http handler and returns pattern and http handler for (*http.ServeMux).Handle-like methods.

func Profiler

func Profiler(prefix string) (string, http.Handler)

Profiler adds the given prefix to the profiler handler and returns pattern and http handler for (*http.ServeMux).Handle-like methods.

func ProfilerHandler

func ProfilerHandler() http.Handler

ProfilerHandler returns http handler that provides /pprof routes.

func RealIP

func RealIP(r *http.Request) net.IP

RealIP extracts real ip from X-Forward-For and X-Real-IP headers.

func Set

func Set[T any](r *http.Request, key string, value T)

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

type Middleware func(next http.Handler) http.Handler

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 NewRouter added in v1.4.0

func NewRouter() *Router

NewRouter creates a new Router.

func (*Router) Group added in v1.4.0

func (r *Router) Group(prefix string, fn func(group *Router))

Group creates a new router group with prefix.

func (*Router) Handle added in v1.4.0

func (r *Router) Handle(pattern string, handler http.Handler)

Handle registers the handler for the given pattern.

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) Mount added in v1.6.0

func (r *Router) Mount(prefix string, handler http.Handler)

Mount attaches handler as a subrouter with prefix.

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.

Jump to

Keyboard shortcuts

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