fire

package module
v0.0.0-...-3811ee0 Latest Latest
Warning

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

Go to latest
Published: Mar 29, 2026 License: MIT Imports: 20 Imported by: 0

README

🔥 Fire

Fire is a fast web framework for Go, similar in its API to Fiber. In fact, it's almost a complete drop-in replacement for Fiber v3.

This is still in a very early stage of development: it is not at all production ready. Contributions are welcome. Expect improvements over the coming months.

Installing

Note that there are no tagged releases yet, so if you would like to try out Fire, please use our main branch:

go get -u codeberg.org/gofire/fire@main

Usage

func main() {
	app := fire.New()
	app.Get("/", func(c fire.Ctx) error {
		return c.JSON(fire.Map{
			"hello": "world",
		})
	})
	app.Listen(":8080")
}

Relation to Fiber

The only relation to Fiber in this project is its overall API, with some differences:

  • Ctx.Set() becomes Ctx.SetHeader()
  • Ctx.Get() becomes Ctx.Header()
  • Ctx.Get(fiber.HeaderUserAgent) can be done via Ctx.UserAgent()
  • Ctx.Set() with Content-Type is simplified to Ctx.SetContentType()
  • Ctx.Status() becomes Ctx.WithStatus()
  • Ctx.Params() becomes Ctx.Param()
  • Ctx.Locals() becomes Ctx.Local() and Ctx.SetLocal()
  • fiber.Locals[T]() becomes fire.Local[T]()
  • Ctx.RequestCtx() becomes Ctx.Context()

There's also some additional features, such as the github.com/SeraphSecure/bodies/v3 package integrated directly into Fire as fire.ParseModValidate[T] and derivatives.

License

MIT license.

Documentation

Index

Constants

View Source
const (
	SchemeHttp  = "http"
	SchemeHttps = "https"
)

Schemes

View Source
const (
	MethodGet     = "GET"
	MethodHead    = "HEAD"
	MethodPost    = "POST"
	MethodPut     = "PUT"
	MethodPatch   = "PATCH" // RFC 5789
	MethodDelete  = "DELETE"
	MethodConnect = "CONNECT"
	MethodOptions = "OPTIONS"
	MethodTrace   = "TRACE"
)

HTTP method names copied from net/http

View Source
const (
	StatusContinue           = 100 // RFC 9110, 15.2.1
	StatusSwitchingProtocols = 101 // RFC 9110, 15.2.2
	StatusProcessing         = 102 // RFC 2518, 10.1
	StatusEarlyHints         = 103 // RFC 8297

	StatusOK                   = 200 // RFC 9110, 15.3.1
	StatusCreated              = 201 // RFC 9110, 15.3.2
	StatusAccepted             = 202 // RFC 9110, 15.3.3
	StatusNonAuthoritativeInfo = 203 // RFC 9110, 15.3.4
	StatusNoContent            = 204 // RFC 9110, 15.3.5
	StatusResetContent         = 205 // RFC 9110, 15.3.6
	StatusPartialContent       = 206 // RFC 9110, 15.3.7
	StatusMultiStatus          = 207 // RFC 4918, 11.1
	StatusAlreadyReported      = 208 // RFC 5842, 7.1
	StatusIMUsed               = 226 // RFC 3229, 10.4.1

	StatusMultipleChoices  = 300 // RFC 9110, 15.4.1
	StatusMovedPermanently = 301 // RFC 9110, 15.4.2
	StatusFound            = 302 // RFC 9110, 15.4.3
	StatusSeeOther         = 303 // RFC 9110, 15.4.4
	StatusNotModified      = 304 // RFC 9110, 15.4.5
	StatusUseProxy         = 305 // RFC 9110, 15.4.6

	StatusTemporaryRedirect = 307 // RFC 9110, 15.4.8
	StatusPermanentRedirect = 308 // RFC 9110, 15.4.9

	StatusBadRequest                   = 400 // RFC 9110, 15.5.1
	StatusUnauthorized                 = 401 // RFC 9110, 15.5.2
	StatusPaymentRequired              = 402 // RFC 9110, 15.5.3
	StatusForbidden                    = 403 // RFC 9110, 15.5.4
	StatusNotFound                     = 404 // RFC 9110, 15.5.5
	StatusMethodNotAllowed             = 405 // RFC 9110, 15.5.6
	StatusNotAcceptable                = 406 // RFC 9110, 15.5.7
	StatusProxyAuthRequired            = 407 // RFC 9110, 15.5.8
	StatusRequestTimeout               = 408 // RFC 9110, 15.5.9
	StatusConflict                     = 409 // RFC 9110, 15.5.10
	StatusGone                         = 410 // RFC 9110, 15.5.11
	StatusLengthRequired               = 411 // RFC 9110, 15.5.12
	StatusPreconditionFailed           = 412 // RFC 9110, 15.5.13
	StatusRequestEntityTooLarge        = 413 // RFC 9110, 15.5.14
	StatusRequestURITooLong            = 414 // RFC 9110, 15.5.15
	StatusUnsupportedMediaType         = 415 // RFC 9110, 15.5.16
	StatusRequestedRangeNotSatisfiable = 416 // RFC 9110, 15.5.17
	StatusExpectationFailed            = 417 // RFC 9110, 15.5.18
	StatusTeapot                       = 418 // RFC 9110, 15.5.19 (Unused)
	StatusMisdirectedRequest           = 421 // RFC 9110, 15.5.20
	StatusUnprocessableEntity          = 422 // RFC 9110, 15.5.21
	StatusLocked                       = 423 // RFC 4918, 11.3
	StatusFailedDependency             = 424 // RFC 4918, 11.4
	StatusTooEarly                     = 425 // RFC 8470, 5.2.
	StatusUpgradeRequired              = 426 // RFC 9110, 15.5.22
	StatusPreconditionRequired         = 428 // RFC 6585, 3
	StatusTooManyRequests              = 429 // RFC 6585, 4
	StatusRequestHeaderFieldsTooLarge  = 431 // RFC 6585, 5
	StatusUnavailableForLegalReasons   = 451 // RFC 7725, 3

	StatusInternalServerError           = 500 // RFC 9110, 15.6.1
	StatusNotImplemented                = 501 // RFC 9110, 15.6.2
	StatusBadGateway                    = 502 // RFC 9110, 15.6.3
	StatusServiceUnavailable            = 503 // RFC 9110, 15.6.4
	StatusGatewayTimeout                = 504 // RFC 9110, 15.6.5
	StatusHTTPVersionNotSupported       = 505 // RFC 9110, 15.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 copied from net/http

View Source
const (
	ContentTypeTextPlain           = "text/plain"
	ContentTypeTextPlainUTF8       = "text/plain; charset=utf-8"
	ContentTypeTextHtml            = "text/html"
	ContentTypeTextHtmlUTF8        = "text/html; charset=utf-8"
	ContentTypeTextXml             = "text/xml"
	ContentTypeTextXmlUTF8         = "text/xml; charset=utf-8"
	ContentTypeForm                = "application/x-www-form-urlencoded"
	ContentTypeFormUTF8            = "application/x-www-form-urlencoded; charset=utf-8"
	ContentTypeApplicationXml      = "application/xml"
	ContentTypeApplicationXmlUTF8  = "application/xml; charset=utf-8"
	ContentTypeApplicationJson     = "application/json"
	ContentTypeApplicationJsonUTF8 = "application/json; charset=utf-8"
	ContentTypeOctetStream         = "application/octet-stream"
)

MIME types for the Content-Type header

Variables

View Source
var (
	ErrBadRequest           = NewError(StatusBadRequest, "bad request")
	ErrUnauthorized         = NewError(StatusUnauthorized, "unauthorized")
	ErrPaymentRequired      = NewError(StatusPaymentRequired, "payment required")
	ErrForbidden            = NewError(StatusForbidden, "forbidden")
	ErrNotFound             = NewError(StatusNotFound, "not found")
	ErrMethodNotAllowed     = NewError(StatusMethodNotAllowed, "method not allowed")
	ErrNotAcceptable        = NewError(StatusNotAcceptable, "not acceptable")
	ErrTooManyRequests      = NewError(StatusTooManyRequests, "too many requests")
	ErrUnsupportedMediaType = NewError(StatusUnsupportedMediaType, "unsupported media type")
)

Functions

func BindMod

func BindMod(c Ctx, out any) error

Binds the body of the request into an existing out value and runs any "mod" transformations on it. This does NOT run any validations on it; see BindModValidate[T] for that.

func BindModValidate

func BindModValidate(c Ctx, out any) error

Binds the body of the request into an existing out value, runs any "mod" transformations on it followed by "validate" validators.

func BindValidate

func BindValidate(c Ctx, out any) error

Binds the body of the request into an existing out value and runs any "validate" validators on it. This does NOT run any transformations on it; see BindModValidate[T] for that.

func DefaultErrorHandler

func DefaultErrorHandler(c Ctx, err error) error

The default error handler, providing plaintext error output

func GetErrorStatusCode

func GetErrorStatusCode(err error) int

Gets the presumed status code for the given error

func GetTransformer

func GetTransformer() *mold.Transformer

func GetValidator

func GetValidator() *validator.Validate

func Local

func Local[T any](c Ctx, name string) T

func Mod

func Mod(ctx context.Context, v any) error

Runs any "mod" transformations on the given struct. To combine this with body parsing, see ParseMod[T].

func ModValidate

func ModValidate(ctx context.Context, v any) error

Runs any "mod" transformations on the given struct, followed by any "validate" validators. To combine this with body parsing as well, see ParseModValidate[T] or BindModValidate[T].

func Parse

func Parse[T any](c Ctx) (T, error)

Parses the body of the request into an instance of T. Does not perform any transformations or validations. See also ParseValidate[T] and ParseModValidate[T].

func ParseMod

func ParseMod[T any](c Ctx) (T, error)

Parses the body of the request into an instance of T and runs any "mod" transformations on it. This does NOT run any validations on it; see ParseModValidate[T] for that.

func ParseModValidate

func ParseModValidate[T any](c Ctx) (T, error)

Parses the body of the request into an instance of T, runs any "mod" transformations on it followed by "validate" validators.

func ParseValidate

func ParseValidate[T any](c Ctx) (T, error)

Parses the body of the request into an instance of T and runs any "validate" validators on it. This does NOT run any transformations on it; see ParseModValidate[T] for that.

func Query

func Query[T any](c Ctx, name string, def ...T) T

func UnsafeBytes

func UnsafeBytes(s string) []byte

UnsafeBytes returns a byte pointer without allocation

func UnsafeString

func UnsafeString(b []byte) string

UnsafeString returns a string pointer without allocation

func Validate

func Validate(v any) error

Runs any "validate" validators on the given struct. To combine this with body parsing, see ParseValidate[T].

Types

type App

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

func New

func New(config ...Config) *App

func (*App) Delete

func (a *App) Delete(path string, handlers ...Handler)

func (*App) Get

func (a *App) Get(path string, handlers ...Handler)

func (*App) Group

func (a *App) Group(path string, handlers ...Handler) Router

func (*App) Listen

func (a *App) Listen(addr string) error

func (*App) Patch

func (a *App) Patch(path string, handlers ...Handler)

func (*App) Post

func (a *App) Post(path string, handlers ...Handler)

func (*App) Put

func (a *App) Put(path string, handlers ...Handler)

func (*App) Shutdown

func (a *App) Shutdown() error

func (*App) Use

func (a *App) Use(handlers ...Handler)

type Bind

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

func (*Bind) Body

func (b *Bind) Body(out any) error

func (*Bind) Form

func (b *Bind) Form(out any) error

func (*Bind) JSON

func (b *Bind) JSON(out any) error

func (*Bind) Query

func (b *Bind) Query(out any) error

func (*Bind) XML

func (b *Bind) XML(out any) error

type Config

type Config struct {
	// Handler to use when errors occur. Defaults to fire.DefaultErrorHandler.
	ErrorHandler ErrorHandler

	// What header to use for the list of forwarded IPs. Defaults to "X-Forwarded-For".
	ProxyHeaderForwardedFor string

	// Whether to trust proxy headers, see also TrustProxyConfig. Defaults to false.
	TrustProxy bool

	// Configuration for trusted proxies.
	TrustProxyConfig TrustProxyConfig

	// Which logger to use for any internal log purposes. Defaults to fire.Logger.
	Logger fasthttp.Logger

	// Optional logger specifically for fasthttp messages. Defaults to fire.SilentLogger.
	FastHttpLogger fasthttp.Logger

	// Renderer to use for Ctx.Render*. Defaults to nil.
	Renderer Renderer
}

type Ctx

type Ctx interface {
	App() *App
	Request() *fasthttp.Request
	Context() *fasthttp.RequestCtx

	Scheme() string
	Hostname() string
	Method() string
	Path() string
	BaseURL() string

	Bind() *Bind

	Param(name string, def ...string) string
	ParamInt(name string, def ...int) int
	ParamUint(name string, def ...uint) uint

	Queries() map[string]string
	Query(name string, def ...string) string
	QueryInt(name string, def ...int) int
	QueryUint(name string, def ...uint) uint

	PostArgs() map[string]string
	PostArg(name string, def ...string) string
	PostArgInt(name string, def ...int) int
	PostArgUint(name string, def ...uint) uint

	IP() string
	IPs() []string
	UserAgent() string

	Header(name string) string
	SetHeader(name, setValue string)

	Cookie(name string) string
	SetCookie(name, setValue string, params ...SetCookieParams)
	DeleteCookie(name string, params ...DeleteCookieParams)

	MediaType() string
	ContentType() string
	SetContentType(setValue string)

	Next() error
	Drop() error

	Local(name string) any
	SetLocal(name string, setValue any)

	Redirect() Redirect

	WithStatus(code int) Ctx
	SendStatus(code int) error

	Render(view string, data ...any) error
	RenderLayout(layout, view string, data ...any) error
	RenderPartial(view string, data ...any) (string, error)

	Send(bytes []byte) error
	SendString(str string) error
	SendStream(stream io.Reader, size ...int) error
	JSON(obj any) error

	Write(p []byte) (n int, err error)
}

type DeleteCookieParams

type DeleteCookieParams struct {
	// See also SetCookieParams.Domain.
	Domain string

	// See also SetCookieParams.Path. Defaults to "/".
	Path string
}

type Error

type Error struct {
	Code    int
	Message string
}

func NewError

func NewError(code int, message string) *Error

Create a new error with the given status code

func (*Error) Error

func (e *Error) Error() string

type ErrorHandler

type ErrorHandler func(c Ctx, err error) error

func MakeJsonErrorHandler

func MakeJsonErrorHandler(config ...JsonErrorHandlerConfig) ErrorHandler

Make a default json error handler with the given configuration

func MakeRenderErrorHandler

func MakeRenderErrorHandler(view string) ErrorHandler

Make a default rendering error handler with the given view

type FieldValidationError

type FieldValidationError struct {
	Field string `json:"field"`
	Tag   string `json:"tag"`
	Param string `json:"param,omitempty"`
}

Field validation error used by the json error handler - see MakeJsonErrorHandler() and JsonErrorHandlerConfig

type Group

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

func (*Group) Delete

func (g *Group) Delete(path string, handlers ...Handler)

func (*Group) Get

func (g *Group) Get(path string, handlers ...Handler)

func (*Group) Group

func (g *Group) Group(path string, handlers ...Handler) Router

func (*Group) Patch

func (g *Group) Patch(path string, handlers ...Handler)

func (*Group) Post

func (g *Group) Post(path string, handlers ...Handler)

func (*Group) Put

func (g *Group) Put(path string, handlers ...Handler)

func (*Group) Use

func (g *Group) Use(handlers ...Handler)

type Handler

type Handler func(c Ctx) error

type JsonErrorHandlerConfig

type JsonErrorHandlerConfig struct {
	// Whether to include detailed field validation errors. Defaults to false.
	ValidationErrors bool

	// The field name for validation errors. Only used if ValidationErrors is true.
	// Defaults to "validation_errors".
	ValidationErrorsField string

	// Whether to include the "param" field from validation errors. Defaults to false.
	ValidationErrorsParam bool
}

Configuration that can be passed to MakeJsonErrorHandler()

type Logger

type Logger struct{}

func (*Logger) Printf

func (l *Logger) Printf(format string, args ...any)

type Map

type Map map[string]any

type Redirect

type Redirect interface {
	// Redirect with status 307.
	Temporary() Redirect
	// Redirect with status 308.
	Permanent() Redirect

	// Redirect with status 301.
	MovedPermanently() Redirect
	// Redirect with status 302.
	Found() Redirect
	// Redirect with status 303. This is the default.
	SeeOther() Redirect

	// Perform the redirect.
	To(to string) error
	// Redirects to the referer or the fallback if set.
	Back(fallback string) error
}

type Renderer

type Renderer interface {
	Render(c Ctx, view string, data ...any) error
	RenderLayout(c Ctx, layout, view string, data ...any) error
	RenderPartial(c Ctx, view string, data ...any) (string, error)
}

type Route

type Route struct {
	Path   RoutePath `json:"path"`
	Method string    `json:"method"`
	// contains filtered or unexported fields
}

func (*Route) CheckRouteParams

func (r *Route) CheckRouteParams(rp *routeParams) error

func (*Route) RunHandlers

func (r *Route) RunHandlers(c *ctx) error

type RoutePath

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

func ParseRoutePath

func ParseRoutePath(path string) RoutePath

func (RoutePath) Append

func (p RoutePath) Append(other RoutePath) RoutePath

func (RoutePath) IndexOfParam

func (p RoutePath) IndexOfParam(param string) int

func (RoutePath) IsMatch

func (p RoutePath) IsMatch(matchParts []string) bool

func (RoutePath) String

func (p RoutePath) String() string

type Router

type Router interface {
	Use(handlers ...Handler)

	Group(path string, handlers ...Handler) Router
	Get(path string, handlers ...Handler)
	Post(path string, handlers ...Handler)
	Put(path string, handlers ...Handler)
	Delete(path string, handlers ...Handler)
	Patch(path string, handlers ...Handler)
	// contains filtered or unexported methods
}

type SetCookieParams

type SetCookieParams struct {
	// Defines the host to which the cookie will be sent. Only the current domain
	// can be set as the value, or a domain of a higher order, unless it is a
	// public suffix. Setting the domain will make the cookie available to it, as
	// well as to all its subdomains.
	Domain string

	// Indicates the path that must exist in the requested URL for the browser to
	// send the Cookie header. Defaults to "/".
	Path string

	// Controls whether or not a cookie is sent with cross-site requests: that is,
	// requests originating from a different site, including the scheme, from the
	// site that set the cookie. This provides some protection against certain
	// cross-site attacks, including cross-site request forgery (CSRF) attacks.
	//
	// For more information, see: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Set-Cookie#samesitesamesite-value
	SameSite fasthttp.CookieSameSite

	// Indicates the maximum lifetime of the cookie as an HTTP-date timestamp. If
	// unspecified, the cookie becomes a session cookie. A session finishes when
	// the client shuts down, after which the session cookie is removed.
	ExpireTime time.Time

	// Indicates the number of seconds until the cookie expires. A zero or
	// negative number will expire the cookie immediately. If both Expiretime and
	// MaxAge are set, MaxAge has precedence.
	MaxAge int

	// Forbids JavaScript from accessing the cookie, for example, through the
	// Document.cookie property.
	HTTPOnly bool

	// Indicates that the cookie is sent to the server only when a request is made
	// with the https: scheme (except on localhost), and therefore, is more
	// resistant to man-in-the-middle attacks.
	Secure bool

	// Indicates that the cookie should be stored using partitioned storage. Note
	// that if this is set, the Secure directive must also be set.
	Partitioned bool
}

Parameters to be passed to Ctx.SetCookie.

Some documentation below taken from MDN for convenience from: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Set-Cookie by Mozilla Contributors, licensed under CC-BY-SA 2.5

type SilentLogger

type SilentLogger struct{}

func (*SilentLogger) Printf

func (l *SilentLogger) Printf(format string, args ...any)

type TrustProxyConfig

type TrustProxyConfig struct {

	// List of IP specific ranges/addresses to trust. Defaults to an empty list.
	Proxies []string

	// Whether to trust the private IP ranges 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, and fd00::/8. Defaults to false.
	Private bool

	// Whether to trust localhost IP range 127.0.0.0/8 and ::1. Defaults to false.
	Loopback bool

	// Whether to trust link-local IP ranges 169.254.0.0/16 and fe80::/10. Defaults to false.
	LinkLocal bool
	// contains filtered or unexported fields
}

func (TrustProxyConfig) IsTrusted

func (tpc TrustProxyConfig) IsTrusted(ip net.IP) bool

func (*TrustProxyConfig) ParseProxies

func (tpc *TrustProxyConfig) ParseProxies() error

Parses the public Proxies into the private cached pre-parsed fields.

Directories

Path Synopsis
extra

Jump to

Keyboard shortcuts

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