xrest

package module
v1.2.6 Latest Latest
Warning

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

Go to latest
Published: Apr 16, 2025 License: MIT Imports: 21 Imported by: 0

README

Utilities for developing REST applications

Note

Documentation() uses Stoplight Elements for serving OpenAPI documentation.

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)

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
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, &params); err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		xrest.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"},
		"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 Debug deprecated

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

Deprecated: use Profiler.

func Documentation

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

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

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

Returns http handler that provides OpenAPI specification page. Uses Stoplight Elements.

func Error

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

func File

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

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)

func GetError

func GetError(r *http.Request) error

func Group

func Group(prefix string, fn func() http.Handler) (string, http.Handler)

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

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

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

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

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

func ProfilerHandler() http.Handler

Returns http handler that provides /pprof routes.

func RealIP added in v1.2.0

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

func Set

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

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

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

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

func NewRouter() *Router

func (*Router) Group added in v1.1.0

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

func (*Router) Handle added in v1.1.0

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

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)

Jump to

Keyboard shortcuts

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