there

package module
v2.2.4 Latest Latest
Warning

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

Go to latest
Published: May 4, 2024 License: MIT Imports: 19 Imported by: 0

Documentation

Index

Constants

View Source
const (
	MethodGet     = "GET"
	MethodHead    = "HEAD"
	MethodPost    = "POST"
	MethodPut     = "PUT"
	MethodPatch   = "PATCH" // RFC 5789
	MethodDelete  = "DELETE"
	MethodConnect = "CONNECT"
	MethodOptions = "OPTIONS"
	MethodTrace   = "TRACE"
)
View Source
const (
	ContentTypeApplicationJavaDashArchive                = "application/java-archive"
	ContentTypeApplicationEdiDashX12                     = "application/EDI-X12"
	ContentTypeApplicationEdifact                        = "application/EDIFACT"
	ContentTypeApplicationJavascript                     = "application/javascript"
	ContentTypeApplicationOctetDashStream                = "application/octet-stream"
	ContentTypeApplicationOgg                            = "application/ogg"
	ContentTypeApplicationPdf                            = "application/pdf"
	ContentTypeApplicationXhtmlPlusXml                   = "application/xhtml+xml"
	ContentTypeApplicationXDashShockwaveDashFlash        = "application/x-shockwave-flash"
	ContentTypeApplicationJson                           = "application/json"
	ContentTypeApplicationMsgpack                        = "application/x-msgpack"
	ContentTypeApplicationLdPlusJson                     = "application/ld+json"
	ContentTypeApplicationXml                            = "application/xml"
	ContentTypeApplicationZip                            = "application/zip"
	ContentTypeApplicationXDashWwwDashFormDashUrlencoded = "application/x-www-form-urlencoded"
	ContentTypeAudioMpeg                                 = "audio/mpeg"
	ContentTypeAudioXDashMsDashWma                       = "audio/x-ms-wma"
	ContentTypeAudioVndDotRnDashRealaudio                = "audio/vnd.rn-realaudio"
	ContentTypeAudioXDashWav                             = "audio/x-wav"
	ContentTypeImageGif                                  = "image/gif"
	ContentTypeImageJpeg                                 = "image/jpeg"
	ContentTypeImagePng                                  = "image/png"
	ContentTypeImageTiff                                 = "image/tiff"
	ContentTypeImageVndDotMicrosoftDotIcon               = "image/vnd.microsoft.icon"
	ContentTypeImageXDashIcon                            = "image/x-icon"
	ContentTypeImageVndDotDjvu                           = "image/vnd.djvu"
	ContentTypeImageSvgPlusXml                           = "image/svg+xml"
	ContentTypeMultipartMixed                            = "multipart/mixed"
	ContentTypeMultipartAlternative                      = "multipart/alternative"
	ContentTypeMultipartRelated                          = "multipart/related"
	ContentTypeMultipartFormDashData                     = "multipart/form-data"
	ContentTypeTextCss                                   = "text/css"
	ContentTypeTextCsv                                   = "text/csv"
	ContentTypeTextHtml                                  = "text/html"
	ContentTypeTextJavascript                            = "text/javascript"
	ContentTypeTextPlain                                 = "text/plain"
	ContentTypeTextXml                                   = "text/xml"
	ContentTypeVideoMpeg                                 = "video/mpeg"
	ContentTypeVideoMp4                                  = "video/mp4"
	ContentTypeVideoQuicktime                            = "video/quicktime"
	ContentTypeVideoXDashMsDashWmv                       = "video/x-ms-wmv"
	ContentTypeVideoXDashMsvideo                         = "video/x-msvideo"
	ContentTypeVideoXDashFlv                             = "video/x-flv"
	ContentTypeVideoWebm                                 = "video/webm"
)

Variables

View Source
var AutoHandlers = map[string]func(code int, data any) Response{
	"fallback":                 Json,
	ContentTypeApplicationJson: Json,
	ContentTypeApplicationXml:  Xml,
}
View Source
var (
	ErrorParameterNotPresent = errors.New("parameter not present")
)

Functions

func ContentType added in v2.2.1

func ContentType(extension string) string

ContentType returns a content type header based on a given file-serving extension. The second returned var indicates, whether that content type was found in the list or not.

func NegotiateContentType added in v2.2.1

func NegotiateContentType(headerValue, offers []string, defaultOffer string) string

NegotiateContentType returns the best offered content type for the request's Accept header. If two offers match with equal weight, then the more specific offer is preferred. For example, text/* trumps */*. If two offers match with equal weight and specificity, then the offer earlier in the list is preferred. If no offers match, then defaultOffer is returned.

Types

type AcceptSpec added in v2.2.1

type AcceptSpec struct {
	Value string
	Q     float64
}

AcceptSpec describes an Accept* header.

func ParseAccept added in v2.2.1

func ParseAccept(header []string) (specs []AcceptSpec)

ParseAccept parses Accept* headers.

type BodyReader

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

BodyReader reads the body and unmarshal it to the specified destination

func (BodyReader) BindJson

func (read BodyReader) BindJson(dest any) error

func (BodyReader) BindXml

func (read BodyReader) BindXml(dest any) error

func (BodyReader) ToBytes

func (read BodyReader) ToBytes() ([]byte, error)

func (BodyReader) ToString

func (read BodyReader) ToString() (string, error)

type Endpoint

type Endpoint func(request Request) Response

type MapReader added in v2.2.1

type MapReader map[string][]string

MapReader reads http params

func (MapReader) Get added in v2.2.1

func (reader MapReader) Get(key string) (string, bool)

func (MapReader) GetDefault added in v2.2.1

func (reader MapReader) GetDefault(key, defaultValue string) string

func (MapReader) GetInt added in v2.2.1

func (reader MapReader) GetInt(key string) (int, error)

func (MapReader) GetIntDefault added in v2.2.1

func (reader MapReader) GetIntDefault(key string, defaultValue int) int

func (MapReader) GetIntSlice added in v2.2.1

func (reader MapReader) GetIntSlice(key, delimiter string) ([]int, error)

func (MapReader) GetIntSliceDefault added in v2.2.1

func (reader MapReader) GetIntSliceDefault(key, delimiter string, defaultValue []int) []int

func (MapReader) GetSlice added in v2.2.1

func (reader MapReader) GetSlice(key string) ([]string, bool)

func (MapReader) Has added in v2.2.1

func (reader MapReader) Has(key string) bool

type Middleware

type Middleware func(request Request, next Response) Response

type Port

type Port uint16

func (Port) ToAddr

func (p Port) ToAddr() string

type Request added in v2.2.1

type Request struct {
	Request        *http.Request
	ResponseWriter http.ResponseWriter

	Method        string
	Body          *BodyReader
	Params        *MapReader
	Headers       *MapReader
	RouteParams   *RouteParamReader
	RemoteAddress string
	Host          string
	URI           string
}

func NewHttpRequest

func NewHttpRequest(responseWriter http.ResponseWriter, request *http.Request) Request

func (*Request) Context added in v2.2.1

func (r *Request) Context() context.Context

func (*Request) WithContext added in v2.2.1

func (r *Request) WithContext(ctx context.Context)

type Response added in v2.2.1

type Response http.Handler

Response is the base for every return you can make in an Endpoint. Necessary to render the Response by calling Execute and for the Headers Builder.

func Auto added in v2.2.1

func Auto(code int, data any) Response

func Bytes

func Bytes(code int, data []byte) Response

Bytes writes the data parameter with the given status code to the http.ResponseWriter

The Content-Type header is set to nothing at all.

func ExampleStringGet(request there.Request) there.Response {
	return there.String(status.OK, "Hello there")
}

When this handler gets called, the final rendered result will be

Hello there

func Error

func Error(code int, err error) Response

Error builds a json response using the err parameter and writes the result with the given status code to the http.ResponseWriter

The Content-Type header is set accordingly to application/json

func ExampleErrorGet(request there.Request) there.Response {
	if 1 != 2 {
		return there.Error(status.InternalServerError, errors.New("something went wrong"))
	}
	return there.Status(status.OK)
}

When this handler gets called, the final rendered result will be

{"error":"something went wrong"}

For optimal performance the use of json.Marshal is avoided and the response body is built directly. With this way, there is no error that could occur.

func File added in v2.2.1

func File(path string, contentType ...string) Response

File returns the contents of the file provided by the path. The content type gets automatically guessed by the file extension. If the extension is unknown, then the fallback ContentType is ContentTypeTextPlain. Additionally, a custom ContentType can be set, by providing a second argument.

func Gzip added in v2.2.1

func Gzip(response Response) Response

Gzip wraps around your current Response and compresses all the data written to it, if the client has specified 'gzip' in the Accept-Encoding header.

func Headers added in v2.2.1

func Headers(headers map[string]string, response Response) Response

Headers wraps around your current Response and sets all the headers parsed in the headers parameter provided they are not set. If a header was already set by a previous Response, then it will be skipped.

func Cors(configuration CorsConfiguration) there.Middleware {
	return func(request there.Request, next there.Response) there.Response {
		headers := map[string]string{
			header.ResponseAccessControlAllowOrigin:  configuration.AccessControlAllowOrigin,
			header.ResponseAccessControlAllowMethods: configuration.AccessControlAllowMethods,
			header.ResponseAccessControlAllowHeaders: configuration.AccessControlAllowHeaders,
		}
		if request.Method == there.MethodOptions {
			return there.Headers(headers, there.Status(status.OK))
		}
		return there.Headers(headers, next)
	}
}

When this middleware gets called, all the Cors Headers will be set.

func Html

func Html(code int, file string, template any) Response

Html takes a status code, the path to the html file and a map for the template parsing

func Json

func Json(code int, data any) Response

Json marshalls the given data parameter with the json.Marshal function and writes the result with the given status code to the http.ResponseWriter

The Content-Type header is set accordingly to application/json

func ExampleGet(request there.Request) there.Response {
	user := map[string]string{
		"firstname": "John",
		"surname": "Smith",
	}
	return there.Json(status.OK, user)
}

When this handler gets called, the final rendered result will be

{"firstname":"John","surname":"Smith"}

If the json.Marshal fails with an error, then an Error with StatusInternalServerError will be returned, with the error format "json: json.Marshal: %v"

func JsonError added in v2.2.1

func JsonError(code int, data any) (Response, error)

JsonError marshalls the given data parameter with the json.Marshal function and writes the result with the given status code to the http.ResponseWriter

The Content-Type header is set accordingly to application/json

func ExampleJsonErrorGet(request there.Request) there.Response{
	user := map[string]string{
		"firstname": "John",
		"surname": "Smith",
	}
	resp, err := there.JsonError(status.OK, user)
	if err != nil {
		return there.Error(status.InternalServerError, fmt.Errorf("something went wrong: %v", err))
	}
	return resp
}

When this handler gets called, the final rendered result will be

{"firstname":"John","surname":"Smith"}

If the json.Marshal fails with an error, then a nil response with a non-nil error will be returned to handle.

func Message

func Message(code int, message string) Response

Message builds a json response using the message parameter and writes the result with the given status code to the http.ResponseWriter

The Content-Type header is set accordingly to application/json

func ExampleMessageGet(request there.Request) there.Response {
	return there.Message(status.OK, "Hello there")
}

When this handler gets called, the final rendered result will be

{"message":"Hello there"}

For optimal performance the use of json.Marshal is avoided and the response body is built directly. With this way, there is no error that could occur.

func Redirect

func Redirect(code int, url string) Response

Redirect redirects to the specific URL

func Status added in v2.1.0

func Status(code int) Response

Status sets the given status code to the http.ResponseWriter.

No Content-Type header is set at all.

func ExampleStatusGet(request there.Request) there.Response {
	return there.Status(status.OK)
}

When this handler gets called, the final rendered result will be an empty body with the status 200

func String

func String(code int, data string) Response

String writes the data parameter with the given status code to the http.ResponseWriter

The Content-Type header is set accordingly to text/plain

func ExampleStringGet(request there.Request) there.Response {
	return there.String(status.OK, "Hello there")
}

When this handler gets called, the final rendered result will be

Hello there

func Xml

func Xml(code int, data any) Response

Xml marshalls the given data parameter with the xml.Marshal function and writes the result with the given status code to the http.ResponseWriter

The Content-Type header is set accordingly to application/xml

type User struct {
	Firstname string `xml:"firstname"`
	Surname string  `xml:"surname"`
}

func ExampleXmlGet(request there.Request) there.Response{
	user := User{"John", "Smith"}
	return there.Xml(status.OK, user)
}

When this handler gets called, the final rendered result will be

<User><firstname>John</firstname><surname>Smith</surname></User>

If the xml.Marshal fails with an error, then an Error with StatusInternalServerError will be returned, with the error format "xml: xml.Marshal: %v"

func XmlError added in v2.2.1

func XmlError(code int, data any) (Response, error)

XmlError marshalls the given data parameter with the xml.Marshal function and writes the result with the given status code to the http.ResponseWriter

The Content-Type header is set accordingly to application/xml

type User struct {
	Firstname string `xml:"firstname"`
	Surname   string `xml:"surname"`
}

func ExampleXmlErrorGet(request there.Request) there.Response {
	user := User{"John", "Smith"}
	resp, err := there.XmlError(status.OK, user)
	if err != nil {
		return there.Error(status.InternalServerError, fmt.Errorf("something went wrong: %v", err))
	}
	return resp
}

When this handler gets called, the final rendered result will be

<User><firstname>John</firstname><surname>Smith</surname></User>

If the xml.Marshal fails with an error, then a nil response with a non-nil error will be returned to handle.

type ResponseFunc added in v2.2.1

type ResponseFunc func(http.ResponseWriter, *http.Request)

ResponseFunc is the type for a http.Handler

func (ResponseFunc) ServeHTTP added in v2.2.1

func (f ResponseFunc) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP calls f(w, r).

type Route

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

Route adds attributes to an Endpoint func

type RouteGroup

type RouteGroup struct {
	*Router
	// contains filtered or unexported fields
}

func NewRouteGroup

func NewRouteGroup(router *Router, route string) *RouteGroup

func (*RouteGroup) Connect

func (group *RouteGroup) Connect(route string, endpoint Endpoint) *RouteRouteGroupBuilder

func (*RouteGroup) Delete

func (group *RouteGroup) Delete(route string, endpoint Endpoint) *RouteRouteGroupBuilder

func (*RouteGroup) Get

func (group *RouteGroup) Get(route string, endpoint Endpoint) *RouteRouteGroupBuilder

func (RouteGroup) Group

func (group RouteGroup) Group(prefix string) *RouteGroup

func (*RouteGroup) Handle

func (group *RouteGroup) Handle(path string, endpoint Endpoint, methodsString ...string) *RouteRouteGroupBuilder

func (RouteGroup) HasError added in v2.2.1

func (a RouteGroup) HasError() error

func (*RouteGroup) Head

func (group *RouteGroup) Head(route string, endpoint Endpoint) *RouteRouteGroupBuilder

func (*RouteGroup) Options

func (group *RouteGroup) Options(route string, endpoint Endpoint) *RouteRouteGroupBuilder

func (*RouteGroup) Patch

func (group *RouteGroup) Patch(route string, endpoint Endpoint) *RouteRouteGroupBuilder

func (*RouteGroup) Post

func (group *RouteGroup) Post(route string, endpoint Endpoint) *RouteRouteGroupBuilder

func (*RouteGroup) Put

func (group *RouteGroup) Put(route string, endpoint Endpoint) *RouteRouteGroupBuilder

func (*RouteGroup) Trace

func (group *RouteGroup) Trace(route string, endpoint Endpoint) *RouteRouteGroupBuilder

type RouteParamReader

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

func (RouteParamReader) Get

func (reader RouteParamReader) Get(key string) string

type RouteRouteGroupBuilder

type RouteRouteGroupBuilder struct {
	*Route
	*RouteGroup
}

func (RouteRouteGroupBuilder) HasError added in v2.2.1

func (a RouteRouteGroupBuilder) HasError() error

func (*RouteRouteGroupBuilder) With added in v2.0.7

func (group *RouteRouteGroupBuilder) With(middleware Middleware) *RouteRouteGroupBuilder

With adds a middleware to the handler the method is called on

type Router

type Router struct {
	*RouteGroup
	Configuration *RouterConfiguration
	Server        *http.Server
	// contains filtered or unexported fields
}

func NewRouter

func NewRouter() *Router

func (*Router) HasError added in v2.2.1

func (a *Router) HasError() error

func (*Router) Listen

func (router *Router) Listen(port Port) error

func (*Router) ListenToTLS

func (router *Router) ListenToTLS(port Port, certFile, keyFile string) error

func (*Router) ServeHTTP

func (router *Router) ServeHTTP(rw http.ResponseWriter, request *http.Request)

func (*Router) Use

func (router *Router) Use(middleware ...Middleware) *Router

Use registers a Middleware

type RouterConfiguration

type RouterConfiguration struct {
	// RouteNotFoundHandler gets invoked, when the specified URL and method have no handlers
	RouteNotFoundHandler Endpoint
	SanitizePaths        bool
}

RouterConfiguration is a straightforward place to override default behavior of the router

Jump to

Keyboard shortcuts

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