lite

package module
v0.0.8 Latest Latest
Warning

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

Go to latest
Published: Jul 6, 2024 License: MIT Imports: 19 Imported by: 0

README

Lite Logo

Go Go Reference Go Report Card codecov

Lite: A Typed Wrapper for GoFiber

Lite is a typed wrapper for GoFiber, a web framework for Go. It is designed to be lightweight and easy to use, while still providing a powerful API for building web applications. Lite is built on top of GoFiber, so it inherits all of its features and performance benefits.

Features

  • Typed Requests: Define request types to ensure correct data handling.
  • Typed Responses: Define response types to ensure correct data serialization.
  • Error Handling: Simplify error management with typed responses.
  • Middleware: Use middleware to add functionality to your routes.
  • OpenAPI Specification: Generate OpenAPI specs from your routes.

Installation

To install Lite, use go get:

go get github.com/go-lite/lite

Usage

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"))
}

Contributing

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

License

Lite is licensed under the MIT License. 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-Version"

	// 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

This section is empty.

Functions

func NewOpenAPISpec

func NewOpenAPISpec() openapi3.T

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 {
	*fiber.App

	OpenAPISpec   openapi3.T
	OpenAPIConfig OpenAPIConfig

	Serializer func(ctx *fasthttp.RequestCtx, response any) error
	// contains filtered or unexported fields
}

func Group

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

func New

func New() *App

func (*App) AddServer

func (s *App) AddServer(url, description string)

AddServer adds a server to the OpenAPI spec

func (*App) AddTags

func (s *App) AddTags(tags ...string) *App

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

func (*App) Description

func (s *App) Description(description string) *App

Description sets the description of the OpenAPI spec

func (*App) Listen

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

func (*App) SaveOpenAPISpec

func (s *App) SaveOpenAPISpec() ([]byte, error)

SaveOpenAPISpec saves the OpenAPI spec to a file in YAML format

func (*App) Shutdown

func (s *App) Shutdown() error

func (*App) Title

func (s *App) Title(title string) *App

Title sets the title of the OpenAPI spec

func (*App) Version

func (s *App) Version(version string) *App

Version sets the version of the OpenAPI spec

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
	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 string, 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) 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 string, 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 string, 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 OpenAPIConfig

type OpenAPIConfig struct {
	DisableSwagger   bool                               // If true, the server will not serve the swagger ui nor the openapi json spec
	DisableLocalSave bool                               // If true, the server will not save the openapi json spec locally
	SwaggerURL       string                             // URL to serve the swagger ui
	UIHandler        func(specURL string) fiber.Handler // Handler to serve the openapi ui from spec url
	YamlURL          string                             // Local path to save the openapi json spec
}

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]) 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 string) Route[ResponseBody, Request]

func (Route[ResponseBody, Request]) Summary

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

Directories

Path Synopsis
examples
basic command
file command

Jump to

Keyboard shortcuts

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