fire

package module
v0.0.0-...-01674ed Latest Latest
Warning

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

Go to latest
Published: Mar 2, 2026 License: MIT Imports: 17 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() and Ctx.Get() is replaced with a single Ctx.Header()
  • Ctx.Get(fiber.HeaderUserAgent) can be done via Ctx.UserAgent()
  • Ctx.Get and Ctx.Set with the Content-Type header is simplified to Ctx.ContentType()
  • Ctx.Status() becomes Ctx.WithStatus()
  • Ctx.Params() becomes the singular Ctx.Param()
  • Ctx.Locals() becomes the singular Ctx.Local()
  • fiber.Locals[T]() becomes the singular 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")
)

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

func GetTransformer

func GetTransformer() *mold.Transformer

func GetValidator

func GetValidator() *validator.Validate

func JsonErrorHandler

func JsonErrorHandler(c Ctx, err error) error

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) Routes

func (a *App) Routes() *SubRoute

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) Reset

func (b *Bind) Reset(c *ctx)

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
}

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

	Header(name string, setValue ...string) string
	IP() string
	IPs() []string
	UserAgent() string
	ContentType(setValue ...string) string
	MediaType() string

	Next() error
	Drop() error
	Local(name string, setValue ...any) any

	Redirect() Redirect

	WithStatus(code int) Ctx
	SendStatus(code int) 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 Error

type Error struct {
	Code    int
	Message string
}

func NewError

func NewError(code int, message string) *Error

func (*Error) Error

func (e *Error) Error() string

type ErrorHandler

type ErrorHandler func(c Ctx, err error) error

type Handler

type Handler func(c Ctx) error

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 Route

type Route struct {
	Part   RoutePart `json:"part"`
	Method string    `json:"method"`

	Parent *SubRoute `json:"-"`
	// contains filtered or unexported fields
}

func (Route) IndexOfParam

func (r Route) IndexOfParam(param string) int

func (Route) RunHandlers

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

type RoutePart

type RoutePart string

func (RoutePart) IsCatchAll

func (r RoutePart) IsCatchAll() bool

func (RoutePart) IsMatch

func (r RoutePart) IsMatch(part string) bool

func (RoutePart) IsParameter

func (r RoutePart) IsParameter() bool

func (RoutePart) ParameterName

func (r RoutePart) ParameterName() 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)
}

type SubRoute

type SubRoute struct {
	Part  RoutePart `json:"part"`
	Depth int       `json:"depth"`

	Routes   []*Route `json:"routes"`
	CatchAll *Route   `json:"catchall"`

	Parent    *SubRoute   `json:"-"`
	SubRoutes []*SubRoute `json:"subroutes"`
}

func (*SubRoute) FindRouteFromPath

func (sr *SubRoute) FindRouteFromPath(method, path string) (*Route, error)

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

Directories

Path Synopsis
extra

Jump to

Keyboard shortcuts

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