lite

package module
v0.1.23 Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2024 License: MIT Imports: 31 Imported by: 0

README

Lite Logo

Go Go Reference Go Report Card codecov

Lite: A Typed Wrapper for GoFiber

Overview

The lite package provides functionalities for automatically generating OpenAPI documentation for HTTP operations based on the struct definitions and their tags within a Go application. This document explains how to use the lite package, specifically focusing on the usage of the lite tag.

Installation

To use the lite package, you need to install it first. Assuming you have Go installed, you can add it to your project with:

go get github.com/go-lite/lite

Usage

Simple Example

Here is a simple example of how to use Lite:

package main

import (
	"github.com/go-lite/lite"
	"log"
)

type Response struct {
	Message string `json:"message"`
}

func main() {
	app := lite.New()

	lite.Get(app, "/", func(c *lite.ContextNoRequest) (Response, error) {
		return Response{Message: "Hello, world!"}, nil
	})

	log.Fatal(app.Listen(":3000"))
}

The swagger specs is available at http://localhost:3000/swagger/index.html if port 3000 is used.

Other Example
package main

import (
	"io"
	"log"
	"mime/multipart"
	"os"

	"github.com/go-lite/lite"
	"github.com/go-lite/lite/errors"
	"github.com/go-lite/lite/mime"
	"github.com/gofiber/fiber/v2/middleware/logger"
	"github.com/gofiber/fiber/v2/middleware/recover"
)

type ImageResponse = []byte

type ImagePayload struct {
	Body Image `lite:"req=body,multipart/form-data"`
}

type Image struct {
	Info  info                  `form:"info"`
	Image *multipart.FileHeader `form:"image"`
}

type info struct {
	FileName string `form:"filename"`
}

func main() {
	app := lite.New()

	lite.Use(app, logger.New())
	lite.Use(app, recover.New())

	lite.Post(app, "/v1/image/analyse", func(c *lite.ContextWithRequest[ImagePayload]) (ImageResponse, error) {
		req, err := c.Requests()
		if err != nil {
			return ImageResponse{}, errors.NewBadRequestError(err.Error())
		}

		image := req.Body.Image

		if err = c.SaveFile(image, "./examples/file/uploads/"+image.Filename); err != nil {
			return ImageResponse{}, err
		}

		// get the file
		f, err := os.Open("./examples/file/uploads/" + image.Filename)
		if err != nil {
			return ImageResponse{}, err
		}

		// Dummy data for the response
		response, err := io.ReadAll(f)
		if err != nil {
			log.Fatalf("failed reading file: %s", err)
		}

		c.SetContentType(mime.ImagePng)

		return response, nil
	}).SetResponseContentType("image/png")
	lite.Post(app, "/v1/pdf", func(c *lite.ContextWithRequest[[]byte]) (any, error) {
		req, err := c.Requests()
		if err != nil {
			return nil, errors.NewBadRequestError(err.Error())
		}

		log.Println(string(req))

		return nil, nil
	})

	app.AddServer("http://localhost:9000", "example server")

	if err := app.Run(); err != nil {
		return
	}
}
Supported Tags

The lite package supports the following tags within struct definitions to map fields to different parts of an HTTP request or response:

Tag SetDescription Example
params Maps to a URL path parameter lite:"params=id"
query Maps to a URL query parameter lite:"query=name"
header Maps to an HTTP header lite:"header=Auth"
cookie Maps to an HTTP cookie lite:"cookie=session_id"
req Maps to the request body lite:"req=body"
enums Maps to a string enums enums:"male,female"

Contributing

Contributions are welcome! Please feel free to submit a pull request or open an issue.

SetLicense

Lite is licensed under the MIT SetLicense. See LICENSE for more information. []: # (END)

Documentation

Index

Constants

View Source
const (
	// Authentication.
	HeaderAuthorization      = "Authorization"
	HeaderProxyAuthenticate  = "Proxy-Authenticate"
	HeaderProxyAuthorization = "Proxy-Authorization"
	HeaderWWWAuthenticate    = "WWW-Authenticate"

	// Caching.
	HeaderAge           = "Age"
	HeaderCacheControl  = "Cache-Control"
	HeaderClearSiteData = "Clear-Site-Data"
	HeaderExpires       = "Expires"
	HeaderPragma        = "Pragma"
	HeaderWarning       = "Warning"

	// Client hints.
	HeaderAcceptCH         = "Accept-CH"
	HeaderAcceptCHLifetime = "Accept-CH-Lifetime"
	HeaderContentDPR       = "Content-DPR"
	HeaderDPR              = "DPR"
	HeaderEarlyData        = "Early-Data"
	HeaderSaveData         = "Save-Data"
	HeaderViewportWidth    = "Viewport-Width"
	HeaderWidth            = "Width"

	// Conditionals.
	HeaderETag              = "ETag"
	HeaderIfMatch           = "If-Match"
	HeaderIfModifiedSince   = "If-Modified-Since"
	HeaderIfNoneMatch       = "If-None-Match"
	HeaderIfUnmodifiedSince = "If-Unmodified-Since"
	HeaderLastModified      = "Last-Modified"
	HeaderVary              = "Vary"

	// Connection management.
	HeaderConnection      = "Connection"
	HeaderKeepAlive       = "Keep-Alive"
	HeaderProxyConnection = "Proxy-Connection"

	// Content negotiation.
	HeaderAccept         = "Accept"
	HeaderAcceptCharset  = "Accept-Charset"
	HeaderAcceptEncoding = "Accept-Encoding"
	HeaderAcceptLanguage = "Accept-Language"

	// Controls.
	HeaderCookie      = "Cookie"
	HeaderExpect      = "Expect"
	HeaderMaxForwards = "Max-Forwards"
	HeaderSetCookie   = "Set-Cookie"

	// CORS.
	HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials"
	HeaderAccessControlAllowHeaders     = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowMethods     = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowOrigin      = "Access-Control-Allow-Origin"
	HeaderAccessControlExposeHeaders    = "Access-Control-Expose-Headers"
	HeaderAccessControlMaxAge           = "Access-Control-Max-Age"
	HeaderAccessControlRequestHeaders   = "Access-Control-Request-Headers"
	HeaderAccessControlRequestMethod    = "Access-Control-Request-Method"
	HeaderOrigin                        = "Origin"
	HeaderTimingAllowOrigin             = "Timing-Allow-Origin"
	HeaderXPermittedCrossDomainPolicies = "X-Permitted-Cross-Domain-Policies"

	// Do Not Track.
	HeaderDNT = "DNT"
	HeaderTk  = "Tk"

	// Downloads.
	HeaderContentDisposition = "Content-Disposition"

	// Message body information.
	HeaderContentEncoding = "Content-Encoding"
	HeaderContentLanguage = "Content-Language"
	HeaderContentLength   = "Content-Length"
	HeaderContentLocation = "Content-Location"
	HeaderContentType     = "Content-Type"

	// Proxies.
	HeaderForwarded       = "Forwarded"
	HeaderVia             = "Via"
	HeaderXForwardedFor   = "X-Forwarded-For"
	HeaderXForwardedHost  = "X-Forwarded-Host"
	HeaderXForwardedProto = "X-Forwarded-Proto"

	// Redirects.
	HeaderLocation = "Location"

	// Request context.
	HeaderFrom           = "From"
	HeaderHost           = "Host"
	HeaderReferer        = "Referer"
	HeaderReferrerPolicy = "Referrer-Policy"
	HeaderUserAgent      = "User-Agent"

	// Response context.
	HeaderAllow  = "Allow"
	HeaderServer = "Server"

	// Range requests.
	HeaderAcceptRanges = "Accept-Ranges"
	HeaderContentRange = "Content-Range"
	HeaderIfRange      = "If-Range"
	HeaderRange        = "Range"

	// Security.
	HeaderContentSecurityPolicy           = "Content-Security-Policy"
	HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only"
	HeaderCrossOriginResourcePolicy       = "Cross-Origin-Resource-Policy"
	HeaderExpectCT                        = "Expect-CT"
	HeaderFeaturePolicy                   = "Feature-Policy"
	HeaderPublicKeyPins                   = "Public-Key-Pins"
	HeaderPublicKeyPinsReportOnly         = "Public-Key-Pins-Report-Only"
	HeaderStrictTransportSecurity         = "Strict-Transport-Security"
	HeaderUpgradeInsecureRequests         = "Upgrade-Insecure-Requests"
	HeaderXContentTypeOptions             = "X-Content-Type-Options"
	HeaderXDownloadOptions                = "X-Download-Options"
	HeaderXFrameOptions                   = "X-Frame-Options"
	HeaderXPoweredBy                      = "X-Powered-By"
	HeaderXXSSProtection                  = "X-XSS-Protection"

	// Server-sent event.
	HeaderLastEventID = "Last-Event-ID"
	HeaderNEL         = "NEL"
	HeaderPingFrom    = "Ping-From"
	HeaderPingTo      = "Ping-To"
	HeaderReportTo    = "Report-To"

	// Transfer coding.
	HeaderTE               = "TE"
	HeaderTrailer          = "Trailer"
	HeaderTransferEncoding = "Transfer-Encoding"

	// WebSockets.
	HeaderSecWebSocketAccept     = "Sec-WebSocket-Accept"
	HeaderSecWebSocketExtensions = "Sec-WebSocket-Extensions" /* #nosec G101 */
	HeaderSecWebSocketKey        = "Sec-WebSocket-Key"
	HeaderSecWebSocketProtocol   = "Sec-WebSocket-Protocol"
	HeaderSecWebSocketVersion    = "Sec-WebSocket-SetVersion"

	// Other.
	HeaderAcceptPatch         = "Accept-Patch"
	HeaderAcceptPushPolicy    = "Accept-Push-Policy"
	HeaderAcceptSignature     = "Accept-Signature"
	HeaderAltSvc              = "Alt-Svc"
	HeaderDate                = "Date"
	HeaderIndex               = "Index"
	HeaderLargeAllocation     = "Large-Allocation"
	HeaderLink                = "Link"
	HeaderPushPolicy          = "Push-Policy"
	HeaderRetryAfter          = "Retry-After"
	HeaderServerTiming        = "Server-Timing"
	HeaderSignature           = "Signature"
	HeaderSignedHeaders       = "Signed-Headers"
	HeaderSourceMap           = "SourceMap"
	HeaderUpgrade             = "Upgrade"
	HeaderXDNSPrefetchControl = "X-DNS-Prefetch-Control"
	HeaderXPingback           = "X-Pingback"
	HeaderXRequestedWith      = "X-Requested-With"
	HeaderXRobotsTag          = "X-Robots-Tag"
	HeaderXUACompatible       = "X-UA-Compatible"
)

Headers.

View Source
const (
	StatusContinue           = 100 // RFC 7231, 6.2.1
	StatusSwitchingProtocols = 101 // RFC 7231, 6.2.2
	StatusProcessing         = 102 // RFC 2518, 10.1
	StatusEarlyHints         = 103 // RFC 8297

	StatusOK                   = 200 // RFC 7231, 6.3.1
	StatusCreated              = 201 // RFC 7231, 6.3.2
	StatusAccepted             = 202 // RFC 7231, 6.3.3
	StatusNonAuthoritativeInfo = 203 // RFC 7231, 6.3.4
	StatusNoContent            = 204 // RFC 7231, 6.3.5
	StatusResetContent         = 205 // RFC 7231, 6.3.6
	StatusPartialContent       = 206 // RFC 7233, 4.1
	StatusMultiStatus          = 207 // RFC 4918, 11.1
	StatusAlreadyReported      = 208 // RFC 5842, 7.1
	StatusIMUsed               = 226 // RFC 3229, 10.4.1

	StatusMultipleChoices  = 300 // RFC 7231, 6.4.1
	StatusMovedPermanently = 301 // RFC 7231, 6.4.2
	StatusFound            = 302 // RFC 7231, 6.4.3
	StatusSeeOther         = 303 // RFC 7231, 6.4.4
	StatusNotModified      = 304 // RFC 7232, 4.1
	StatusUseProxy         = 305 // RFC 7231, 6.4.5

	StatusTemporaryRedirect = 307 // RFC 7231, 6.4.7
	StatusPermanentRedirect = 308 // RFC 7538, 3

	StatusBadRequest                   = 400 // RFC 7231, 6.5.1
	StatusUnauthorized                 = 401 // RFC 7235, 3.1
	StatusPaymentRequired              = 402 // RFC 7231, 6.5.2
	StatusForbidden                    = 403 // RFC 7231, 6.5.3
	StatusNotFound                     = 404 // RFC 7231, 6.5.4
	StatusMethodNotAllowed             = 405 // RFC 7231, 6.5.5
	StatusNotAcceptable                = 406 // RFC 7231, 6.5.6
	StatusProxyAuthRequired            = 407 // RFC 7235, 3.2
	StatusRequestTimeout               = 408 // RFC 7231, 6.5.7
	StatusConflict                     = 409 // RFC 7231, 6.5.8
	StatusGone                         = 410 // RFC 7231, 6.5.9
	StatusLengthRequired               = 411 // RFC 7231, 6.5.10
	StatusPreconditionFailed           = 412 // RFC 7232, 4.2
	StatusRequestEntityTooLarge        = 413 // RFC 7231, 6.5.11
	StatusRequestURITooLong            = 414 // RFC 7231, 6.5.12
	StatusUnsupportedMediaType         = 415 // RFC 7231, 6.5.13
	StatusRequestedRangeNotSatisfiable = 416 // RFC 7233, 4.4
	StatusExpectationFailed            = 417 // RFC 7231, 6.5.14
	StatusTeapot                       = 418 // RFC 7168, 2.3.3
	StatusMisdirectedRequest           = 421 // RFC 7540, 9.1.2
	StatusUnprocessableEntity          = 422 // RFC 4918, 11.2
	StatusLocked                       = 423 // RFC 4918, 11.3
	StatusFailedDependency             = 424 // RFC 4918, 11.4
	StatusUpgradeRequired              = 426 // RFC 7231, 6.5.15
	StatusPreconditionRequired         = 428 // RFC 6585, 3
	StatusTooManyRequests              = 429 // RFC 6585, 4
	StatusRequestHeaderFieldsTooLarge  = 431 // RFC 6585, 5
	StatusUnavailableForLegalReasons   = 451 // RFC 7725, 3

	StatusInternalServerError           = 500 // RFC 7231, 6.6.1
	StatusNotImplemented                = 501 // RFC 7231, 6.6.2
	StatusBadGateway                    = 502 // RFC 7231, 6.6.3
	StatusServiceUnavailable            = 503 // RFC 7231, 6.6.4
	StatusGatewayTimeout                = 504 // RFC 7231, 6.6.5
	StatusHTTPVersionNotSupported       = 505 // RFC 7231, 6.6.6
	StatusVariantAlsoNegotiates         = 506 // RFC 2295, 8.1
	StatusInsufficientStorage           = 507 // RFC 4918, 11.5
	StatusLoopDetected                  = 508 // RFC 5842, 7.2
	StatusNotExtended                   = 510 // RFC 2774, 7
	StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6
)

HTTP status codes were stolen from net/http.

Variables

View Source
var DefaultErrorContentTypeResponses = []string{
	"application/json",
	"application/xml",
	"multipart/form-data",
}
View Source
var DefaultErrorResponses = map[int]HTTPError{
	StatusBadRequest:          NewBadRequestError("Bad Request"),
	StatusInternalServerError: NewInternalServerError("Internal Server Error"),
}

Functions

func StatusMessage

func StatusMessage(statusCode int) string

StatusMessage returns HTTP status message for the given status code.

func Use

func Use(app *App, args ...any)

Types

type App

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

func Group

func Group(app *App, path string) *App

func New

func New(config ...Config) *App

func (*App) Listen

func (s *App) Listen(address string) error

func (*App) Run added in v0.1.0

func (s *App) Run() error

func (*App) Shutdown

func (s *App) Shutdown() error

type BadRequestError added in v0.1.21

type BadRequestError HTTPError

func (BadRequestError) Error added in v0.1.21

func (e BadRequestError) Error() string

func (BadRequestError) StatusCode added in v0.1.21

func (e BadRequestError) StatusCode() int

type Config added in v0.1.0

type Config func(s *App)

func AddServer added in v0.1.16

func AddServer(url, description string) Config

AddServer adds a server to the OpenAPI spec

func AddTags added in v0.1.16

func AddTags(tags ...*openapi3.Tag) Config

AddTags adds tags from the Server (i.e Group) Tags from the parent Groups will be respected

func SetAddress added in v0.1.0

func SetAddress(address string) Config

func SetContact added in v0.1.16

func SetContact(contact *openapi3.Contact) Config

SetContact sets the contact of the OpenAPI spec

func SetDescription added in v0.1.16

func SetDescription(description string) Config

SetDescription sets the description of the OpenAPI spec

func SetDisableLocalSave added in v0.1.0

func SetDisableLocalSave(disable bool) Config

func SetDisableSwagger added in v0.1.0

func SetDisableSwagger(disable bool) Config

func SetLicense added in v0.1.16

func SetLicense(license *openapi3.License) Config

SetLicense sets the license of the OpenAPI spec

func SetLogger added in v0.1.21

func SetLogger(logger *slog.Logger) Config

func SetOpenAPIPath added in v0.1.0

func SetOpenAPIPath(path string) Config

func SetSwaggerURL added in v0.1.0

func SetSwaggerURL(url string) Config

func SetTermsOfService added in v0.1.16

func SetTermsOfService(termsOfService string) Config

SetTermsOfService sets the terms of service of the OpenAPI spec

func SetTitle added in v0.1.16

func SetTitle(title string) Config

SetTitle sets the title of the OpenAPI spec

func SetTypeOfExtension added in v0.1.0

func SetTypeOfExtension(extension TypeOfExtension) Config

func SetUIHandler added in v0.1.0

func SetUIHandler(handler func(specURL string) fiber.Handler) Config

func SetValidator added in v0.1.21

func SetValidator(v *validator.Validate) Config

func SetVersion added in v0.1.16

func SetVersion(version string) Config

SetVersion sets the version of the OpenAPI spec

type ConflictError added in v0.1.21

type ConflictError HTTPError

func (ConflictError) Error added in v0.1.21

func (e ConflictError) Error() string

func (ConflictError) StatusCode added in v0.1.21

func (e ConflictError) StatusCode() int

type ContentType added in v0.1.21

type ContentType string
const (
	ContentTypeHTML        ContentType = "text/html"
	ContentTypeCSS         ContentType = "text/css"
	ContentTypeXML         ContentType = "application/xml"
	ContentTypeGIF         ContentType = "image/gif"
	ContentTypeJPEG        ContentType = "image/jpeg"
	ContentTypeJS          ContentType = "text/javascript"
	ContentTypeATOM        ContentType = "application/atom+xml"
	ContentTypeRSS         ContentType = "application/rss+xml"
	ContentTypeMML         ContentType = "text/mathml"
	ContentTypeTXT         ContentType = "text/plain"
	ContentTypeJAD         ContentType = "text/vnd.sun.j2me.app-descriptor"
	ContentTypeWML         ContentType = "text/vnd.wap.wml"
	ContentTypeHTC         ContentType = "text/x-component"
	ContentTypeAVIF        ContentType = "image/avif"
	ContentTypePNG         ContentType = "image/png"
	ContentTypeSVG         ContentType = "image/svg+xml"
	ContentTypeTIFF        ContentType = "image/tiff"
	ContentTypeWBMP        ContentType = "image/vnd.wap.wbmp"
	ContentTypeWEBP        ContentType = "image/webp"
	ContentTypeICO         ContentType = "image/x-icon"
	ContentTypeJNG         ContentType = "image/x-jng"
	ContentTypeBMP         ContentType = "image/x-ms-bmp"
	ContentTypeWOFF        ContentType = "font/woff"
	ContentTypeWOFF2       ContentType = "font/woff2"
	ContentTypeJAR         ContentType = "application/java-archive"
	ContentTypeJSON        ContentType = "application/json"
	ContentTypeHQX         ContentType = "application/mac-binhex40"
	ContentTypeDOC         ContentType = "application/msword"
	ContentTypePDF         ContentType = "application/pdf"
	ContentTypePS          ContentType = "application/postscript"
	ContentTypeRTF         ContentType = "application/rtf"
	ContentTypeM3U8        ContentType = "application/vnd.apple.mpegurl"
	ContentTypeKML         ContentType = "application/vnd.google-earth.kml+xml"
	ContentTypeKMZ         ContentType = "application/vnd.google-earth.kmz"
	ContentTypeXLS         ContentType = "application/vnd.ms-excel"
	ContentTypeEOT         ContentType = "application/vnd.ms-fontobject"
	ContentTypePPT         ContentType = "application/vnd.ms-powerpoint"
	ContentTypeODG         ContentType = "application/vnd.oasis.opendocument.graphics"
	ContentTypeODP         ContentType = "application/vnd.oasis.opendocument.presentation"
	ContentTypeODS         ContentType = "application/vnd.oasis.opendocument.spreadsheet"
	ContentTypeODT         ContentType = "application/vnd.oasis.opendocument.text"
	ContentTypePPTX        ContentType = "application/vnd.openxmlformats-officedocument.presentationml.presentation"
	ContentTypeXLSX        ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
	ContentTypeDOCX        ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
	ContentTypeWMLC        ContentType = "application/vnd.wap.wmlc"
	ContentTypeWASM        ContentType = "application/wasm"
	ContentType7Z          ContentType = "application/x-7z-compressed"
	ContentTypeCCO         ContentType = "application/x-cocoa"
	ContentTypeJARDIFF     ContentType = "application/x-java-archive-diff"
	ContentTypeJNLP        ContentType = "application/x-java-jnlp-file"
	ContentTypeRUN         ContentType = "application/x-makeself"
	ContentTypePL          ContentType = "application/x-perl"
	ContentTypePRC         ContentType = "application/x-pilot"
	ContentTypeRAR         ContentType = "application/x-rar-compressed"
	ContentTypeRPM         ContentType = "application/x-redhat-package-manager"
	ContentTypeSEA         ContentType = "application/x-sea"
	ContentTypeSWF         ContentType = "application/x-shockwave-flash"
	ContentTypeSIT         ContentType = "application/x-stuffit"
	ContentTypeTCL         ContentType = "application/x-tcl"
	ContentTypeCRT         ContentType = "application/x-x509-ca-cert"
	ContentTypeXPI         ContentType = "application/x-xpinstall"
	ContentTypeXHTML       ContentType = "application/xhtml+xml"
	ContentTypeXSPF        ContentType = "application/xspf+xml"
	ContentTypeZIP         ContentType = "application/zip"
	ContentTypeMIDI        ContentType = "audio/midi"
	ContentTypeMP3         ContentType = "audio/mpeg"
	ContentTypeOGG         ContentType = "audio/ogg"
	ContentTypeM4A         ContentType = "audio/x-m4a"
	ContentTypeRA          ContentType = "audio/x-realaudio"
	ContentType3GP         ContentType = "video/3gpp"
	ContentTypeTS          ContentType = "video/mp2t"
	ContentTypeMP4         ContentType = "video/mp4"
	ContentTypeMPEG        ContentType = "video/mpeg"
	ContentTypeMOV         ContentType = "video/quicktime"
	ContentTypeWEBM        ContentType = "video/webm"
	ContentTypeFLV         ContentType = "video/x-flv"
	ContentTypeM4V         ContentType = "video/x-m4v"
	ContentTypeMNG         ContentType = "video/x-mng"
	ContentTypeASX         ContentType = "video/x-ms-asf"
	ContentTypeWMV         ContentType = "video/x-ms-wmv"
	ContentTypeAVI         ContentType = "video/x-msvideo"
	ContentTypeXFormData   ContentType = "application/x-www-form-urlencoded"
	ContentTypeFormData    ContentType = "multipart/form-data"
	ContentTypeOctetStream ContentType = "application/octet-stream"
)

type Context

type Context[Request any] interface {
	Context() context.Context
	Requests() (Request, error)
	Accepts(offers ...string) string
	AcceptsCharsets(offers ...string) string
	AcceptsEncodings(offers ...string) string
	AcceptsLanguages(offers ...string) string
	App() *App
	Append(field string, values ...string)
	Attachment(filename ...string)
	BaseURL() string
	BodyRaw() []byte
	ClearCookie(key ...string)
	RequestContext() *fasthttp.RequestCtx
	SetUserContext(ctx context.Context)
	Cookie(cookie *fiber.Cookie)
	Cookies(key string, defaultValue ...string) string
	Download(file string, filename ...string) error
	Request() *fasthttp.Request
	Response() *fasthttp.Response
	Get(key string) string
	Format(body interface{}) error
	Hostname() string
	Port() string
	IP() string
	IPs() []string
	Is(extension string) bool
	Links(link ...string)
	Method(override ...string) string
	OriginalURL() string
	SaveFile(fileheader *multipart.FileHeader, path string) error
	Set(key string, val string)
	Status(status int) Context[Request]
	// SetContentType sets the Content-Type response header with the given type and charset.
	SetContentType(extension mime.Mime, charset ...string) Context[Request]
}

type ContextNoRequest

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

func (*ContextNoRequest) Accepts

func (c *ContextNoRequest) Accepts(offers ...string) string

func (*ContextNoRequest) AcceptsCharsets

func (c *ContextNoRequest) AcceptsCharsets(offers ...string) string

func (*ContextNoRequest) AcceptsEncodings

func (c *ContextNoRequest) AcceptsEncodings(offers ...string) string

func (*ContextNoRequest) AcceptsLanguages

func (c *ContextNoRequest) AcceptsLanguages(offers ...string) string

func (*ContextNoRequest) App

func (c *ContextNoRequest) App() *App

func (*ContextNoRequest) Append

func (c *ContextNoRequest) Append(field string, values ...string)

func (*ContextNoRequest) Attachment

func (c *ContextNoRequest) Attachment(filename ...string)

Attachment adds an attachment to the response.

func (*ContextNoRequest) BaseURL

func (c *ContextNoRequest) BaseURL() string

BaseURL returns the base URL.

func (*ContextNoRequest) BodyRaw

func (c *ContextNoRequest) BodyRaw() []byte

BodyRaw returns the raw body.

func (*ContextNoRequest) ClearCookie

func (c *ContextNoRequest) ClearCookie(key ...string)

ClearCookie clears the cookie.

func (*ContextNoRequest) Context

func (c *ContextNoRequest) Context() context.Context

Context returns the context.

func (*ContextNoRequest) Cookie

func (c *ContextNoRequest) Cookie(cookie *fiber.Cookie)

Cookie sets the cookie.

func (*ContextNoRequest) Cookies

func (c *ContextNoRequest) Cookies(key string, defaultValue ...string) string

Cookies returns the cookie value.

func (*ContextNoRequest) Download

func (c *ContextNoRequest) Download(file string, filename ...string) error

Download downloads the file.

func (*ContextNoRequest) Format

func (c *ContextNoRequest) Format(body interface{}) error

Format formats the response body.

func (*ContextNoRequest) Get added in v0.0.92

func (c *ContextNoRequest) Get(key string) string

func (*ContextNoRequest) Hostname

func (c *ContextNoRequest) Hostname() string

Hostname returns the hostname on which the request is received.

func (*ContextNoRequest) IP

func (c *ContextNoRequest) IP() string

IP returns the client IP.

func (*ContextNoRequest) IPs

func (c *ContextNoRequest) IPs() []string

IPs returns the client IPs.

func (*ContextNoRequest) Is

func (c *ContextNoRequest) Is(extension string) bool

Is returns true if the request has the specified extension.

func (c *ContextNoRequest) Links(link ...string)

Links adds the specified link to the response.

func (*ContextNoRequest) Method

func (c *ContextNoRequest) Method(override ...string) string

Method returns the HTTP method used for the request.

func (*ContextNoRequest) OriginalURL

func (c *ContextNoRequest) OriginalURL() string

OriginalURL returns the original URL.

func (*ContextNoRequest) Port

func (c *ContextNoRequest) Port() string

Port returns the port on which the request is received.

func (*ContextNoRequest) Request

func (c *ContextNoRequest) Request() *fasthttp.Request

Request returns the request.

func (*ContextNoRequest) RequestContext

func (c *ContextNoRequest) RequestContext() *fasthttp.RequestCtx

RequestContext returns the request context.

func (*ContextNoRequest) Requests

func (c *ContextNoRequest) Requests() (any, error)

func (*ContextNoRequest) Response

func (c *ContextNoRequest) Response() *fasthttp.Response

Response returns the response.

func (*ContextNoRequest) SaveFile

func (c *ContextNoRequest) SaveFile(file *multipart.FileHeader, path string) error

SaveFile saves the file to the specified path.

func (*ContextNoRequest) Set

func (c *ContextNoRequest) Set(key string, val string)

Set sets the response's HTTP header field to the specified key, value.

func (*ContextNoRequest) SetContentType

func (c *ContextNoRequest) SetContentType(extension mime.Mime, charset ...string) Context[any]

SetContentType sets the Content-Type response header with the given type and charset.

func (*ContextNoRequest) SetUserContext

func (c *ContextNoRequest) SetUserContext(ctx context.Context)

SetUserContext sets the user context.

func (*ContextNoRequest) Status

func (c *ContextNoRequest) Status(status int) Context[any]

Status sets the HTTP status code.

type ContextWithRequest

type ContextWithRequest[Request any] struct {
	ContextNoRequest
}

func (*ContextWithRequest[Request]) Requests

func (c *ContextWithRequest[Request]) Requests() (Request, error)

func (*ContextWithRequest[Request]) SetContentType

func (c *ContextWithRequest[Request]) SetContentType(extension mime.Mime, charset ...string) Context[Request]

SetContentType sets the Content-Type response header with the given type and charset.

func (*ContextWithRequest[Request]) Status

func (c *ContextWithRequest[Request]) Status(status int) Context[Request]

Status sets the HTTP status code.

type Error added in v0.1.21

type Error interface {
	error
	StatusCode() int
}

type ForbiddenError added in v0.1.21

type ForbiddenError HTTPError

func (ForbiddenError) Error added in v0.1.21

func (e ForbiddenError) Error() string

func (ForbiddenError) StatusCode added in v0.1.21

func (e ForbiddenError) StatusCode() int

type HTTPError added in v0.1.21

type HTTPError struct {
	Context     string      `json:"@context,omitempty"`
	Type        string      `json:"@type,omitempty"`
	Status      int         `json:"status,omitempty"`
	Title       string      `json:"title,omitempty"`
	Description string      `json:"description,omitempty"`
	Violations  []Violation `json:"violations,omitempty"`
}

func NewBadRequestError added in v0.1.21

func NewBadRequestError(descriptions ...string) HTTPError

func NewConflictError added in v0.1.21

func NewConflictError(descriptions ...string) HTTPError

func NewError added in v0.1.21

func NewError(status int, descriptions ...string) HTTPError

func NewErrorResponse added in v0.1.21

func NewErrorResponse(status int, context, title, errorType string, description string, violations []Violation) HTTPError

func NewForbiddenError added in v0.1.21

func NewForbiddenError(descriptions ...string) HTTPError

func NewInternalServerError added in v0.1.21

func NewInternalServerError(descriptions ...string) HTTPError

func NewNotFoundError added in v0.1.21

func NewNotFoundError(descriptions ...string) HTTPError

func NewServiceUnavailableError added in v0.1.21

func NewServiceUnavailableError(descriptions ...string) HTTPError

func NewUnauthorizedError added in v0.1.21

func NewUnauthorizedError(descriptions ...string) HTTPError

func (HTTPError) Descriptions added in v0.1.21

func (e HTTPError) Descriptions() string

func (HTTPError) Error added in v0.1.21

func (e HTTPError) Error() string

func (HTTPError) StatusCode added in v0.1.21

func (e HTTPError) StatusCode() int

type InternalServerError added in v0.1.21

type InternalServerError HTTPError

func (InternalServerError) Error added in v0.1.21

func (e InternalServerError) Error() string

func (InternalServerError) StatusCode added in v0.1.21

func (e InternalServerError) StatusCode() int

type List added in v0.1.0

type List[T any] struct {
	Items  []T `json:"items"`
	Length int `json:"length"`
}

func NewList added in v0.1.0

func NewList[T any](items []T) List[T]

type NotFoundError added in v0.1.21

type NotFoundError HTTPError

func (NotFoundError) Error added in v0.1.21

func (e NotFoundError) Error() string

func (NotFoundError) StatusCode added in v0.1.21

func (e NotFoundError) StatusCode() int

type Route

type Route[T, B any] struct {
	// contains filtered or unexported fields
}

func Connect

func Connect[ResponseBody, Request any, Contexter Context[Request]](
	app *App,
	path string,
	controller func(Contexter) (ResponseBody, error),
	middleware ...fiber.Handler,
) Route[ResponseBody, Request]

func Delete

func Delete[ResponseBody, Request any, Contexter Context[Request]](
	app *App,
	path string,
	controller func(Contexter) (ResponseBody, error),
	middleware ...fiber.Handler,
) Route[ResponseBody, Request]

func Get

func Get[ResponseBody, Request any, Contexter Context[Request]](
	app *App,
	path string,
	controller func(Contexter) (ResponseBody, error),
	middleware ...fiber.Handler,
) Route[ResponseBody, Request]
func Head[ResponseBody, Request any, Contexter Context[Request]](
	app *App,
	path string,
	controller func(Contexter) (ResponseBody, error),
	middleware ...fiber.Handler,
) Route[ResponseBody, Request]

func Options

func Options[ResponseBody, Request any, Contexter Context[Request]](
	app *App,
	path string,
	controller func(Contexter) (ResponseBody, error),
	middleware ...fiber.Handler,
) Route[ResponseBody, Request]

func Patch

func Patch[ResponseBody, Request any, Contexter Context[Request]](
	app *App,
	path string,
	controller func(Contexter) (ResponseBody, error),
	middleware ...fiber.Handler,
) Route[ResponseBody, Request]

func Post

func Post[ResponseBody, Request any, Contexter Context[Request]](
	app *App,
	path string,
	controller func(Contexter) (ResponseBody, error),
	middleware ...fiber.Handler,
) Route[ResponseBody, Request]

func Put

func Put[ResponseBody, Request any, Contexter Context[Request]](
	app *App,
	path string,
	controller func(Contexter) (ResponseBody, error),
	middleware ...fiber.Handler,
) Route[ResponseBody, Request]

func Trace

func Trace[ResponseBody, Request any, Contexter Context[Request]](
	app *App,
	path string,
	controller func(Contexter) (ResponseBody, error),
	middleware ...fiber.Handler,
) Route[ResponseBody, Request]

func (Route[ResponseBody, Request]) AddErrorResponse added in v0.1.16

func (r Route[ResponseBody, Request]) AddErrorResponse(statusCode int, contentType ...ContentType) Route[ResponseBody, Request]

func (Route[ResponseBody, Request]) AddTags

func (r Route[ResponseBody, Request]) AddTags(tags ...string) Route[ResponseBody, Request]

func (Route[ResponseBody, Request]) Deprecated

func (r Route[ResponseBody, Request]) Deprecated() Route[ResponseBody, Request]

func (Route[ResponseBody, Request]) Description

func (r Route[ResponseBody, Request]) Description(description string) Route[ResponseBody, Request]

func (Route[ResponseBody, Request]) OperationID

func (r Route[ResponseBody, Request]) OperationID(operationID string) Route[ResponseBody, Request]

func (Route[ResponseBody, Request]) SetResponseContentType

func (r Route[ResponseBody, Request]) SetResponseContentType(contentType ContentType) Route[ResponseBody, Request]

func (Route[ResponseBody, Request]) Summary

func (r Route[ResponseBody, Request]) Summary(summary string) Route[ResponseBody, Request]

type ServiceUnavailableError added in v0.1.21

type ServiceUnavailableError HTTPError

func (ServiceUnavailableError) Error added in v0.1.21

func (e ServiceUnavailableError) Error() string

func (ServiceUnavailableError) StatusCode added in v0.1.21

func (e ServiceUnavailableError) StatusCode() int

type TypeOfExtension added in v0.1.0

type TypeOfExtension string
const (
	YAMLExtension TypeOfExtension = "yaml"
	JSONExtension TypeOfExtension = "json"
)

type UnauthorizedError added in v0.1.21

type UnauthorizedError HTTPError

func (UnauthorizedError) Error added in v0.1.21

func (e UnauthorizedError) Error() string

func (UnauthorizedError) StatusCode added in v0.1.21

func (e UnauthorizedError) StatusCode() int

type Violation added in v0.1.21

type Violation struct {
	PropertyPath string         `json:"propertyPath,omitempty"`
	Message      string         `json:"message,omitempty"`
	Code         string         `json:"code,omitempty"`
	More         map[string]any `json:"more,omitempty"`
}

Directories

Path Synopsis
jwt

Jump to

Keyboard shortcuts

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