fuego

package module
v0.18.7 Latest Latest
Warning

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

Go to latest
Published: Apr 11, 2025 License: MIT Imports: 35 Imported by: 51

README

Fuego Logo

Fuego 🔥

Go Reference Go Report Card Coverage Status Discord Gophers

The framework for busy Go developers

🚀 Explore and contribute to our 2025 Roadmap! 🚀

Production-ready Go API framework generating OpenAPI documentation from code. Inspired by Nest, built for Go developers.

Also empowers templating with html/template, a-h/templ and maragudk/gomponents: see the example running live.

Sponsors

Fuego is proudly sponsored by Zuplo, that provides a Fuego integration!

Fuego Logo

Zuplo allows you to secure your Fuego API, scale it globally, generate documentation from your OpenAPI, and monetize your users.

Why Fuego?

Chi, Gin, Fiber and Echo are great frameworks. But since they were designed a long time ago, their current API does not allow them to deduce OpenAPI types from signatures, things that are now possible with generics. Fuego offers a lot of "modern Go based" features that make it easy to develop APIs and web applications.

Features

  • OpenAPI: Fuego automatically generates OpenAPI documentation from code - not from comments nor YAML files!
  • 100% net/http compatible (no lock-in): Fuego is built on top of net/http, so you can use any http.Handler middleware or handler! Fuego also supports log/slog, context and html/template.
  • Routing: Fuego router is based on Go 1.22 net/http, with grouping and middleware support
  • Serialization/Deserialization: Fuego automatically serializes and deserializes JSON, XML and HTML Forms based on user-provided structs (or not, if you want to do it yourself)
  • Validation: Fuego provides a simple and fast validator based on go-playground/validator
  • Transformation: easily transform your data by implementing the fuego.InTransform and fuego.OutTransform interfaces - also useful for custom validation
  • Middlewares: easily add a custom net/http middleware or use the provided middlewares.
  • Error handling: Fuego provides centralized error handling with the standard RFC 9457.
  • Rendering: Fuego provides a simple and fast rendering system based on html/template - you can still also use your own template system like templ or gomponents
  • Adaptors: Fuego can be plugged to an existing Gin or Echo server to generate OpenAPI documentation

Examples

Hello World
package main

import "github.com/go-fuego/fuego"

func main() {
	s := fuego.NewServer()

	fuego.Get(s, "/", func(c fuego.ContextNoBody) (string, error) {
		return "Hello, World!", nil
	})

	s.Run()
}
Simple POST
package main

import "github.com/go-fuego/fuego"

type MyInput struct {
	Name string `json:"name" validate:"required"`
}

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

func main() {
	s := fuego.NewServer()

	// Automatically generates OpenAPI documentation for this route
	fuego.Post(s, "/user/{user}", myController)

	s.Run()
}

func myController(c fuego.ContextWithBody[MyInput]) (*MyOutput, error) {
	body, err := c.Body()
	if err != nil {
		return nil, err
	}

	return &MyOutput{Message: "Hello, " + body.Name}, nil
}
With transformation & custom validation
type MyInput struct {
	Name string `json:"name" validate:"required"`
}

// Will be called just before returning c.Body()
func (r *MyInput) InTransform(context.Context) error {
	r.Name = strings.ToLower(r.Name)

	if r.Name == "fuego" {
		return errors.New("fuego is not a valid name for this input")
	}

	return nil
}
More OpenAPI documentation
package main

import (
	"github.com/go-fuego/fuego"
	"github.com/go-fuego/fuego/option"
	"github.com/go-fuego/fuego/param"
)

func main() {
	s := fuego.NewServer()

	// Custom OpenAPI options
	fuego.Post(s, "/", myController,
		option.Description("This route does something..."),
		option.Summary("This is my summary"),
		option.Tags("MyTag"), // A tag is set by default according to the return type (can be deactivated)
		option.Deprecated(),  // Marks the route as deprecated in the OpenAPI spec

		option.Query("name", "Declares a query parameter with default value", param.Default("Carmack")),
		option.Header("Authorization", "Bearer token", param.Required()),
		optionPagination,
		optionCustomBehavior,
	)

	s.Run()
}

var optionPagination = option.Group(
	option.QueryInt("page", "Page number", param.Default(1), param.Example("1st page", 1), param.Example("42nd page", 42)),
	option.QueryInt("perPage", "Number of items per page"),
)

var optionCustomBehavior = func(r *fuego.BaseRoute) {
	r.XXX = "YYY"
}
Std lib compatibility
package main

import (
	"net/http"

	"github.com/go-fuego/fuego"
)

func main() {
	s := fuego.NewServer()

	// Standard net/http middleware
	fuego.Use(s, func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			w.Header().Set("X-Hello", "World")
			next.ServeHTTP(w, r)
		})
	})

	// Standard net/http handler with automatic OpenAPI route declaration
	fuego.GetStd(s, "/std", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("Hello, World!"))
	})

	s.Run()
}
Real-world examples

Please see the /examples folder for more examples.

All features
package main

import (
	"context"
	"errors"
	"net/http"
	"strings"

	chiMiddleware "github.com/go-chi/chi/v5/middleware"
	"github.com/go-fuego/fuego"
	"github.com/rs/cors"
)

type Received struct {
	Name string `json:"name" validate:"required"`
}

type MyResponse struct {
	Message       string `json:"message"`
	BestFramework string `json:"best"`
}

func main() {
	s := fuego.NewServer(
		fuego.WithAddr("localhost:8088"),
	)

	fuego.Use(s, cors.Default().Handler)
	fuego.Use(s, chiMiddleware.Compress(5, "text/html", "text/css"))

	// Fuego 🔥 handler with automatic OpenAPI generation, validation, (de)serialization and error handling
	fuego.Post(s, "/", func(c fuego.ContextWithBody[Received]) (MyResponse, error) {
		data, err := c.Body()
		if err != nil {
			return MyResponse{}, err
		}

		c.Response().Header().Set("X-Hello", "World")

		return MyResponse{
			Message:       "Hello, " + data.Name,
			BestFramework: "Fuego!",
		}, nil
	})

	// Standard net/http handler with automatic OpenAPI route declaration
	fuego.GetStd(s, "/std", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("Hello, World!"))
	})

	s.Run()
}

// InTransform will be called when using c.Body().
// It can be used to transform the entity and raise custom errors
func (r *Received) InTransform(context.Context) error {
	r.Name = strings.ToLower(r.Name)
	if r.Name == "fuego" {
		return errors.New("fuego is not a name")
	}
	return nil
}

// OutTransform will be called before sending data
func (r *MyResponse) OutTransform(context.Context) error {
	r.Message = strings.ToUpper(r.Message)
	return nil
}
curl http://localhost:8088/std
# Hello, World!
curl http://localhost:8088 -X POST -d '{"name": "Your Name"}' -H 'Content-Type: application/json'
# {"message":"HELLO, YOUR NAME","best":"Fuego!"}
curl http://localhost:8088 -X POST -d '{"name": "Fuego"}' -H 'Content-Type: application/json'
# {"error":"cannot transform request body: cannot transform request body: fuego is not a name"}

From net/http to Fuego in 10s

https://github.com/go-fuego/fuego/assets/46993939/7438a71c-75a4-4e88-a584-71da6362c575

Views
Before
image
After
image
Diff
image
Benefits of using Fuego views (controllers returning HTML)
  • Never forget to return after an error
  • OpenAPI schema generated, listing all the routes
  • Deserialization and validation are easier
  • Transition to Fuego is easy and fast

Contributing

See the contributing guide. Thanks to everyone who has contributed to this project! ❤️

Graph of contributors

Made with contrib.rocks

Roadmap

See the board.

Disclaimer for experienced gophers

I know you might prefer to use net/http directly, but if having a frame can convince my company to use Go instead of Node, I'm happy to use it.

License

MIT

Documentation

Overview

Package fuego provides a set of tools to build HTTP servers in Go, that automatically generate OpenAPI 3.0 documentation and support for multiple web frameworks.

Index

Constants

View Source
const JWTCookieName = "jwt_token"

Variables

View Source
var (
	// ErrUnauthorized is used for authorization errors
	//
	// Deprecated: Use [UnauthorizedError] instead.
	ErrUnauthorized = errors.New("unauthorized")
	// ErrTokenNotFound is used when the token is not found
	//
	// Deprecated: Use [UnauthorizedError] instead.
	ErrTokenNotFound = errors.New("token not found")
	// ErrInvalidTokenType is used when the token type is invalid
	//
	// Deprecated: Use [UnauthorizedError] instead.
	ErrInvalidTokenType = errors.New("invalid token type")
	// ErrInvalidRolesType is used when the roles type is invalid
	//
	// Deprecated: Use [UnauthorizedError] instead.
	ErrInvalidRolesType = errors.New("invalid role type. Must be []string")
	// ErrExpired is used when the token is expired
	//
	// Deprecated: Use [ForbiddenError] instead.
	ErrExpired = errors.New("token is expired")
)
View Source
var ReadOptions = readOptions{
	DisallowUnknownFields: true,
	MaxBodySize:           maxBodySize,
}
View Source
var SendError = func(w http.ResponseWriter, r *http.Request, err error) {
	for _, header := range parseAcceptHeader(r.Header) {
		switch inferAcceptHeader(header, nil) {
		case "application/xml":
			SendXMLError(w, nil, err)
		case "text/html":
			SendHTMLError(w, nil, err)
		case "text/plain":
			SendTextError(w, r, err)
		case "application/json":
			SendJSONError(w, nil, err)
		case "application/x-yaml", "text/yaml; charset=utf-8", "application/yaml":
			SendYAMLError(w, nil, err)
		default:
			continue
		}
		return
	}
	SendJSONError(w, r, err)
}

SendError sends an error. Declared as a variable to be able to override it for clients that need to customize serialization.

View Source
var SendHTML = func(w http.ResponseWriter, r *http.Request, ans any) error {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")

	ctxRenderer, ok := ans.(CtxRenderer)
	if ok {
		return ctxRenderer.Render(r.Context(), w)
	}

	renderer, ok := ans.(Renderer)
	if ok {
		return renderer.Render(w)
	}

	html, ok := ans.(HTML)
	if ok {
		_, err := w.Write([]byte(html))
		return err
	}

	htmlString, ok := ans.(string)
	if ok {
		_, err := w.Write([]byte(htmlString))
		return err
	}

	htmlStringRef, ok := ans.(*string)
	if ok {
		_, err := w.Write([]byte(*htmlStringRef))
		return err
	}

	return fmt.Errorf("cannot serialize HTML from type %T (not string, fuego.HTML and does not implement fuego.CtxRenderer or fuego.Renderer)", ans)
}

SendHTML sends a HTML response. Declared as a variable to be able to override it for clients that need to customize serialization.

View Source
var SendJSON = func(w http.ResponseWriter, _ *http.Request, ans any) error {
	w.Header().Set("Content-Type", "application/json")
	err := json.NewEncoder(w).Encode(ans)
	if err != nil {
		slog.Error("Cannot serialize returned response to JSON", "error", err, "errtype", fmt.Sprintf("%T", err))
		var unsupportedType *json.UnsupportedTypeError
		if errors.As(err, &unsupportedType) {
			return NotAcceptableError{
				Err:    err,
				Detail: fmt.Sprintf("Cannot serialize type %T to JSON", ans),
			}
		}
	}
	return err
}

SendJSON sends a JSON response. Declared as a variable to be able to override it for clients that need to customize serialization. If serialization fails, it does NOT write to the response writer. It has to be passed to SendJSONError.

View Source
var SendXML = func(w http.ResponseWriter, _ *http.Request, ans any) error {
	w.Header().Set("Content-Type", "application/xml")
	err := xml.NewEncoder(w).Encode(ans)
	if err != nil {
		slog.Error("Cannot serialize returned response to XML", "error", err, "errtype", fmt.Sprintf("%T", err))
		var unsupportedType *xml.UnsupportedTypeError
		if errors.As(err, &unsupportedType) {
			return NotAcceptableError{
				Err:    err,
				Detail: fmt.Sprintf("Cannot serialize type %T to XML", ans),
			}
		}
	}

	return err
}

SendXML sends a XML response. Declared as a variable to be able to override it for clients that need to customize serialization. If serialization fails, it does NOT write to the response writer. It has to be passed to SendJSONError.

View Source
var SendYAML = func(w http.ResponseWriter, _ *http.Request, ans any) (err error) {

	defer func() {
		if r := recover(); r != nil {
			err = HTTPError{
				Err:    fmt.Errorf("cannot serialize to YAML: %v", r),
				Detail: "Cannot serialize returned response to YAML",
			}
		}
	}()

	w.Header().Set("Content-Type", "application/x-yaml")
	err = yaml.NewEncoder(w).Encode(ans)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		slog.Error("Cannot serialize returned response to YAML", "error", err)
		_, _ = w.Write([]byte(`{"error":"Cannot serialize returned response to YAML"}`))
	}
	return err
}

SendYAML sends a YAML response. Declared as a variable to be able to override it for clients that need to customize serialization. If serialization fails, it does NOT write to the response writer. It has to be passed to SendJSONError.

Functions

func AuthWall

func AuthWall(authorizedRoles ...string) func(next http.Handler) http.Handler

AuthWall is a middleware that checks if the user is authorized. If not, it returns an error. If authorized roles are provided, the user must have at least one of its role in the list. For example:

AuthWall("admin", "chef") // Will block a user with the "waiter" role and allow a user with a role "chef".
AuthWall("chef") // Will block a user with the "admin" and "client" role.
AuthWall() // Will block all users. To simply Check if the user is authenticated, use the [TokenToContext] middleware.

See the tests for more examples.

func AuthWallRegex

func AuthWallRegex(acceptedRolesRegex string) func(next http.Handler) http.Handler

AuthWallRegex is a middleware that checks if the user is authorized. If not, it returns an error. If authorized roles are provided, the user must have at least one of its role in the list that matches the regex. For example:

AuthWallRegex(`^(super)?admin$`) // Will block a user with the "waiter" role and allow a user with a role "admin".

See the tests for more examples.

func AuthWallRegexp

func AuthWallRegexp(acceptedRolesRegex *regexp.Regexp) func(next http.Handler) http.Handler

AuthWallRegexp is a middleware that checks if the user is authorized. If not, it returns an error. If authorized roles are provided, the user must have at least one of its role in the list that matches the regex. For example:

myRegexRule := regexp.MustCompile(`^(super)?admin$`)
AuthWallRegex(myRegexRule) // Will block a user with the "waiter" role and allow a user with a role "admin".

See the tests for more examples.

func DefaultDescription added in v0.17.0

func DefaultDescription[T any](handler string, middlewares []T, middlewareConfig *MiddlewareConfig) string

DefaultDescription returns a default .md description for a controller

func DefaultOpenAPIHTML added in v0.17.0

func DefaultOpenAPIHTML(specURL string) string

func DefaultOpenAPIHandler added in v0.13.0

func DefaultOpenAPIHandler(specURL string) http.Handler

func DisableErrorHandler added in v0.18.0

func DisableErrorHandler() func(*Engine)

DisableErrorHandler overrides ErrorHandler with a simple pass-through

func ErrorHandler

func ErrorHandler(err error) error

ErrorHandler is the default error handler used by the framework. If the error is an HTTPError that error is returned. If the error adheres to the ErrorWithStatus interface the error is transformed to a HTTPError using HandleHTTPError. If the error is not an HTTPError nor does it adhere to an interface the error is returned as is.

func Flow added in v0.17.0

func Flow[B, T any](s *Engine, ctx ContextFlowable[B], controller func(c ContextWithBody[B]) (T, error))

Flow is generic handler for Fuego controllers.

func FuncName added in v0.14.0

func FuncName(f any) string

FuncName returns the name of a function and the name with package path

func GetToken

func GetToken[T any](ctx context.Context) (T, error)

GetToken returns the validated token from the context, if found. To check if the user is authorized, use the AuthWall middleware, or create your own middleware. Example:

token, err := fuego.GetToken[MyCustomTokenType](ctx.Context())

func GroupOptions added in v0.15.0

func GroupOptions(options ...func(*BaseRoute)) func(*BaseRoute)

GroupOptions allows to group routes under a common path. Useful to group often used middlewares or options and reuse them. Example:

optionsPagination := GroupOptions(
	OptionQueryInt("per_page", "Number of items per page", ParamRequired()),
	OptionQueryInt("page", "Page number", ParamDefault(1)),
)

func HTTPHandler added in v0.14.0

func HTTPHandler[ReturnType, Body any](s *Server, controller func(c ContextWithBody[Body]) (ReturnType, error), route BaseRoute) http.HandlerFunc

HTTPHandler converts a Fuego controller into a http.HandlerFunc. Uses Server for configuration. Uses Route for route configuration. Optional.

func HandleHTTPError added in v0.18.3

func HandleHTTPError(err error) error

HandleHTTPError is the core logic of handling fuego HTTPError's. This function takes any error and coerces it into a fuego HTTPError. This can be used override the default handler:

engine := fuego.NewEngine(
	WithErrorHandler(HandleHTTPError),
)

or

server := fuego.NewServer(
	fuego.WithEngineOptions(
		fuego.WithErrorHandler(HandleHTTPError),
	),
)

func InferAcceptHeaderFromType added in v0.14.0

func InferAcceptHeaderFromType(ans any) string

func NewNetHTTPContext added in v0.17.0

func NewNetHTTPContext[B any](route BaseRoute, w http.ResponseWriter, r *http.Request, options readOptions) *netHttpContext[B]

NewNetHTTPContext returns a new context. It is used internally by Fuego. You probably want to use Ctx[B] instead.

func NewOpenApiSpec

func NewOpenApiSpec() openapi3.T

func OptionAddDescription added in v0.16.0

func OptionAddDescription(description string) func(*BaseRoute)

OptionAddDescription appends a description to the route. By default, the description is set by Fuego with some info, like the controller function name and the package name.

func OptionAddError added in v0.15.0

func OptionAddError(code int, description string, errorType ...any) func(*BaseRoute)

OptionAddError adds an error to the route. It replaces any existing error previously set with the same code. Required: should only supply one type to `errorType` Deprecated: Use OptionAddResponse instead

func OptionAddResponse added in v0.17.0

func OptionAddResponse(code int, description string, response Response) func(*BaseRoute)

OptionAddResponse adds a response to a route by status code It replaces any existing response set by any status code, this will override 200. Required: Response.Type must be set Optional: Response.ContentTypes will default to `application/json` and `application/xml` if not set

func OptionCookie added in v0.15.0

func OptionCookie(name, description string, options ...func(*OpenAPIParam)) func(*BaseRoute)

OptionCookie declares a cookie parameter for the route. This will be added to the OpenAPI spec. Example:

OptionCookie("session_id", "Session ID", ParamRequired())

The list of options is in the param package.

func OptionDefaultResponse added in v0.18.3

func OptionDefaultResponse(description string, response Response) func(*BaseRoute)

OptionDefaultResponse adds a default response to a route Required: Response.Type must be set Optional: Response.ContentTypes will default to `application/json` and `application/xml` if not set

func OptionDefaultStatusCode added in v0.16.2

func OptionDefaultStatusCode(defaultStatusCode int) func(*BaseRoute)

OptionDefaultStatusCode sets the default status code for the route.

func OptionDeprecated added in v0.15.0

func OptionDeprecated() func(*BaseRoute)

OptionDeprecated marks the route as deprecated.

func OptionDescription added in v0.15.0

func OptionDescription(description string) func(*BaseRoute)

OptionDescription overrides the default description set by Fuego. By default, the description is set by Fuego with some info, like the controller function name and the package name.

func OptionHeader added in v0.15.0

func OptionHeader(name, description string, options ...func(*OpenAPIParam)) func(*BaseRoute)

OptionHeader declares a header parameter for the route. This will be added to the OpenAPI spec. Example:

OptionHeader("Authorization", "Bearer token", ParamRequired())

The list of options is in the param package.

func OptionHide added in v0.15.0

func OptionHide() func(*BaseRoute)

OptionHide hides the route from the OpenAPI spec.

func OptionMiddleware added in v0.15.0

func OptionMiddleware(middleware ...func(http.Handler) http.Handler) func(*BaseRoute)

OptionMiddleware adds one or more route-scoped middleware.

func OptionOperationID added in v0.15.0

func OptionOperationID(operationID string) func(*BaseRoute)

OptionOperationID adds an operation ID to the route.

func OptionOverrideDescription added in v0.17.0

func OptionOverrideDescription(description string) func(*BaseRoute)

OptionOverrideDescription overrides the default description set by Fuego. By default, the description is set by Fuego with some info, like the controller function name and the package name.

func OptionParam added in v0.15.0

func OptionParam(name string, options ...func(*OpenAPIParam)) func(*BaseRoute)

OptionParam registers a parameter for the route. Prefer using the OptionQuery, OptionQueryInt, OptionHeader, OptionCookie shortcuts.

func OptionPath added in v0.16.0

func OptionPath(name, description string, options ...func(*OpenAPIParam)) func(*BaseRoute)

OptionPath declares a path parameter for the route. This will be added to the OpenAPI spec. It will be marked as required by default by Fuego. Example:

OptionPath("id", "ID of the item")

The list of options is in the param package.

func OptionQuery added in v0.15.0

func OptionQuery(name, description string, options ...func(*OpenAPIParam)) func(*BaseRoute)

OptionQuery declares a query parameter for the route. This will be added to the OpenAPI spec. Example:

OptionQuery("name", "Filter by name", ParamExample("cat name", "felix"), ParamNullable())

The list of options is in the param package.

func OptionQueryBool added in v0.15.0

func OptionQueryBool(name, description string, options ...func(*OpenAPIParam)) func(*BaseRoute)

OptionQueryBool declares a boolean query parameter for the route. This will be added to the OpenAPI spec. The query parameter is transmitted as a string in the URL, but it is parsed as a boolean. Example:

OptionQueryBool("is_active", "Filter by active status", ParamExample("true", true), ParamNullable())

The list of options is in the param package.

func OptionQueryInt added in v0.15.0

func OptionQueryInt(name, description string, options ...func(*OpenAPIParam)) func(*BaseRoute)

OptionQueryInt declares an integer query parameter for the route. This will be added to the OpenAPI spec. The query parameter is transmitted as a string in the URL, but it is parsed as an integer. Example:

OptionQueryInt("age", "Filter by age (in years)", ParamExample("3 years old", 3), ParamNullable())

The list of options is in the param package.

func OptionRequestBody added in v0.18.7

func OptionRequestBody(requestBody RequestBody) func(*BaseRoute)

OptionRequestBody sets a request to a route It replaces existing request body Required: RequestBody.Type must be set Optional: RequestBody.ContentTypes will default to `application/json` and `application/xml` if not set

func OptionRequestContentType added in v0.15.0

func OptionRequestContentType(consumes ...string) func(*BaseRoute)

OptionRequestContentType sets the accepted content types for the route. By default, the accepted content types is */*. This will override any options set at the server level.

func OptionResponseHeader added in v0.16.2

func OptionResponseHeader(name, description string, options ...func(*OpenAPIParam)) func(*BaseRoute)

OptionResponseHeader declares a response header for the route. This will be added to the OpenAPI spec, under the given default status code response. Example:

OptionResponseHeader("Content-Range", "Pagination range", ParamExample("42 pets", "unit 0-9/42"), ParamDescription("https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range"))
OptionResponseHeader("Set-Cookie", "Session cookie", ParamExample("session abc123", "session=abc123; Expires=Wed, 09 Jun 2021 10:18:14 GMT"))

The list of options is in the param package.

func OptionSecurity added in v0.16.0

func OptionSecurity(securityRequirements ...openapi3.SecurityRequirement) func(*BaseRoute)

OptionSecurity configures security requirements to the route.

Single Scheme (AND Logic):

Add a single security requirement with multiple schemes.
All schemes must be satisfied:
OptionSecurity(openapi3.SecurityRequirement{
  "basic": [],        // Requires basic auth
  "oauth2": ["read"]  // AND requires oauth with read scope
})

Multiple Schemes (OR Logic):

Add multiple security requirements.
At least one requirement must be satisfied:
OptionSecurity(
  openapi3.SecurityRequirement{"basic": []},        // First option
  openapi3.SecurityRequirement{"oauth2": ["read"]}  // Alternative option
})

Mixing Approaches:

Combine AND logic within requirements and OR logic between requirements:
OptionSecurity(
  openapi3.SecurityRequirement{
    "basic": [],             // Requires basic auth
    "oauth2": ["read:user"]  // AND oauth with read:user scope
  },
  openapi3.SecurityRequirement{"apiKey": []}  // OR alternative with API key
})

func OptionShow added in v0.17.0

func OptionShow() func(*BaseRoute)

OptionShow shows the route from the OpenAPI spec.

func OptionStripTrailingSlash added in v0.18.7

func OptionStripTrailingSlash() func(*BaseRoute)

OptionStripTrailingSlash ensure that the route declaration will have its ending trailing slash stripped.

func OptionSummary added in v0.15.0

func OptionSummary(summary string) func(*BaseRoute)

OptionSummary adds a summary to the route.

func OptionTags added in v0.15.0

func OptionTags(tags ...string) func(*BaseRoute)

OptionTags adds one or more tags to the route.

func ParamBool added in v0.15.0

func ParamBool() func(param *OpenAPIParam)

func ParamDefault added in v0.15.0

func ParamDefault(value any) func(param *OpenAPIParam)

func ParamDescription added in v0.15.0

func ParamDescription(description string) func(param *OpenAPIParam)

func ParamExample added in v0.15.0

func ParamExample(exampleName string, value any) func(param *OpenAPIParam)

ParamExample adds an example to the parameter. As per the OpenAPI 3.0 standard, the example must be given a name.

func ParamInteger added in v0.15.0

func ParamInteger() func(param *OpenAPIParam)

func ParamNullable added in v0.15.0

func ParamNullable() func(param *OpenAPIParam)

func ParamRequired added in v0.15.0

func ParamRequired() func(param *OpenAPIParam)

func ParamStatusCodes added in v0.16.2

func ParamStatusCodes(codes ...int) func(param *OpenAPIParam)

ParamStatusCodes sets the status codes for which this parameter is required. Only used for response parameters. If empty, it is required for 200 status codes.

func ParamString added in v0.15.0

func ParamString() func(param *OpenAPIParam)

func PathParamIntErr added in v0.18.0

func PathParamIntErr(c ContextWithPathParam, name string) (int, error)

func ReadJSON

func ReadJSON[B any](context context.Context, input io.Reader) (B, error)

ReadJSON reads the request body as JSON. Can be used independently of Fuego framework. Customizable by modifying ReadOptions.

func ReadString

func ReadString[B ~string](context context.Context, input io.Reader) (B, error)

ReadString reads the request body as string. Can be used independently of Fuego framework. Customizable by modifying ReadOptions.

func ReadURLEncoded

func ReadURLEncoded[B any](r *http.Request) (B, error)

ReadURLEncoded reads the request body as HTML Form.

func ReadXML added in v0.13.2

func ReadXML[B any](context context.Context, input io.Reader) (B, error)

ReadXML reads the request body as XML. Can be used independently of Fuego framework. Customizable by modifying ReadOptions.

func ReadYAML added in v0.13.0

func ReadYAML[B any](context context.Context, input io.Reader) (B, error)

ReadYAML reads the request body as YAML. Can be used independently of Fuego framework. Customizable by modifying ReadOptions.

func RegisterOpenAPIOperation deprecated

func RegisterOpenAPIOperation[T, B any](openapi *OpenAPI, route Route[T, B]) (*openapi3.Operation, error)

RegisterOpenAPIOperation registers an OpenAPI operation.

Deprecated: Use `(*Route[ResponseBody, RequestBody]).RegisterOpenAPIOperation` instead.

func Send

func Send(w http.ResponseWriter, r *http.Request, ans any) (err error)

Send sends a response. The format is determined by the Accept header. If Accept header `*/*` is found Send will Attempt to send HTML, and then JSON.

func SendHTMLError added in v0.14.0

func SendHTMLError(w http.ResponseWriter, _ *http.Request, err error)

SendHTMLError sends a HTML response. If the error implements ErrorWithStatus, the status code will be set.

func SendJSONError

func SendJSONError(w http.ResponseWriter, _ *http.Request, err error)

SendJSONError sends a JSON error response. If the error implements ErrorWithStatus, the status code will be set.

func SendText added in v0.14.0

func SendText(w http.ResponseWriter, _ *http.Request, ans any) error

SendText sends a HTML response. Declared as a variable to be able to override it for clients that need to customize serialization.

func SendTextError added in v0.15.0

func SendTextError(w http.ResponseWriter, _ *http.Request, err error)

SendTextError sends a Text response. If the error implements ErrorWithStatus, the status code will be set.

func SendXMLError

func SendXMLError(w http.ResponseWriter, _ *http.Request, err error)

SendXMLError sends a XML error response. If the error implements ErrorWithStatus, the status code will be set.

func SendYAMLError added in v0.15.0

func SendYAMLError(w http.ResponseWriter, _ *http.Request, err error)

SendYAMLError sends a YAML error response. If the error implements ErrorWithStatus, the status code will be set.

func TokenFromContext

func TokenFromContext(ctx context.Context) (jwt.Claims, error)

TokenFromContext returns the validated token from the context, if found. To check if the user is authorized, use the AuthWall middleware, or create your own middleware. Even though it returns a jwt.MapClaims, the real underlying type is the one you chose when calling Security.GenerateToken. Example:

token, err := fuego.TokenFromContext[MyCustomTokenType](ctx.Context())

func TokenFromCookie

func TokenFromCookie(r *http.Request) string

func TokenFromHeader

func TokenFromHeader(r *http.Request) string

func TokenFromQueryParam

func TokenFromQueryParam(r *http.Request) string

func TransformAndValidate added in v0.18.0

func TransformAndValidate[B any](context context.Context, body B) (B, error)

func Use

func Use(s *Server, middlewares ...func(http.Handler) http.Handler)

func UseStd

func UseStd(s *Server, middlewares ...func(http.Handler) http.Handler)

func ValidateParams added in v0.17.0

func ValidateParams(c ValidableCtx) error

ValidateParams checks if all required parameters are present in the request.

func WithAddr added in v0.13.0

func WithAddr(addr string) func(*Server)

WithAddr optionally specifies the TCP address for the server to listen on, in the form "host:port". If not specified addr ':9999' will be used. If a listener is explicitly set using WithListener, the provided address will be ignored,

func WithAutoAuth

func WithAutoAuth(verifyUserInfo func(user, password string) (jwt.Claims, error)) func(*Server)

func WithBasePath

func WithBasePath(basePath string) func(*Server)

func WithCorsMiddleware deprecated added in v0.13.0

func WithCorsMiddleware(corsMiddleware func(http.Handler) http.Handler) func(*Server)

WithCorsMiddleware adds CORS middleware to the server.

Deprecated: Please use WithGlobalMiddlewares instead.

func WithDisallowUnknownFields

func WithDisallowUnknownFields(b bool) func(*Server)

WithDisallowUnknownFields sets the DisallowUnknownFields option. If true, the server will return an error if the request body contains unknown fields. Useful for quick debugging in development. Defaults to true.

func WithEngineOptions added in v0.18.0

func WithEngineOptions(options ...func(*Engine)) func(*Server)

WithEngineOptions allows for setting of Engine options

app := fuego.NewServer(
	fuego.WithAddr(":8080"),
	fuego.WithEngineOptions(
		WithOpenAPIConfig(
			OpenAPIConfig{
				PrettyFormatJSON: true,
			},
		),
	),
)

Engine Options all begin with `With`.

func WithErrorHandler

func WithErrorHandler(errorHandler func(err error) error) func(*Engine)

WithErrorHandler sets a customer error handler for the server

func WithErrorSerializer

func WithErrorSerializer(serializer ErrorSender) func(*Server)

WithErrorSerializer sets a custom serializer of type ErrorSender that overrides the default one. Please send a PR if you think the default serializer should be improved, instead of jumping to this option.

func WithGlobalMiddlewares added in v0.18.0

func WithGlobalMiddlewares(middlewares ...func(http.Handler) http.Handler) func(*Server)

WithGlobalMiddlewares adds middleware(s) that will be executed on ALL requests, even those that don't match any registered routes. Global Middlewares are mounted on the http.Server Handler, when executing Server.Run. Route Middlewares are mounted directly on http.ServeMux added at route registration.

For example, to add CORS middleware:

import "github.com/rs/cors"

s := fuego.NewServer(
	WithGlobalMiddlewares(cors.New(cors.Options{
		AllowedOrigins:   []string{"*"},
		AllowedMethods:   []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
		AllowedHeaders:   []string{"*"},
		AllowCredentials: true,
	}).Handler),
)

func WithGlobalResponseTypes deprecated added in v0.14.0

func WithGlobalResponseTypes(code int, description string, response Response) func(*Server)

WithGlobalResponseTypes adds default response types to the server. For example:

app := fuego.NewServer(
	fuego.WithGlobalResponseTypes(400, "Bad Request _(validation or deserialization error)_", HTTPError{}),
	fuego.WithGlobalResponseTypes(401, "Unauthorized _(authentication error)_", HTTPError{}),
	fuego.WithGlobalResponseTypes(500, "Internal Server Error _(panics)_", HTTPError{}),
	fuego.WithGlobalResponseTypes(204, "No Content", Empty{}),
)

Deprecated: Please use OptionAddResponse with WithRouteOptions

func WithListener added in v0.18.0

func WithListener(listener net.Listener) func(*Server)

WithListener configures the server to use a custom listener. If a listener is provided using this option, any address specified with WithAddr will be ignored.

Example:

listener, _ := net.Listen("tcp", ":8080")
server := NewServer(
    WithListener(listener),
    WithAddr(":9999"), // This will be ignored because WithListener takes precedence.
)

func WithLogHandler added in v0.10.0

func WithLogHandler(handler slog.Handler) func(*Server)

WithLogHandler sets the log handler of the server.

func WithLoggingMiddleware added in v0.18.0

func WithLoggingMiddleware(loggingConfig LoggingConfig) func(*Server)

WithLoggingMiddleware configures the default logging middleware for the server.

func WithMaxBodySize

func WithMaxBodySize(maxBodySize int64) func(*Server)

func WithMiddlewareConfig added in v0.18.1

func WithMiddlewareConfig(cfg MiddlewareConfig) func(*Engine)

func WithOpenAPIConfig added in v0.13.0

func WithOpenAPIConfig(config OpenAPIConfig) func(*Engine)

func WithRequestContentType added in v0.15.0

func WithRequestContentType(consumes ...string) func(*Engine)

WithRequestContentType sets the accepted content types for the engine. By default, the accepted content types is */*.

func WithRouteOptions added in v0.15.1

func WithRouteOptions(options ...func(*BaseRoute)) func(*Server)

func WithSecurity added in v0.16.0

func WithSecurity(schemes openapi3.SecuritySchemes) func(*Server)

WithSecurity configures security schemes in the OpenAPI specification. It allows setting up authentication methods like JWT Bearer tokens, API keys, OAuth2, etc. For example:

app := fuego.NewServer(
	fuego.WithSecurity(map[string]*openapi3.SecuritySchemeRef{
		"bearerAuth": &openapi3.SecuritySchemeRef{
			Value: openapi3.NewSecurityScheme().
				WithType("http").
				WithScheme("bearer").
				WithBearerFormat("JWT").
				WithDescription("Enter your JWT token in the format: Bearer <token>"),
		},
	}),
)

func WithSerializer

func WithSerializer(serializer Sender) func(*Server)

WithSerializer sets a custom serializer of type Sender that overrides the default one. Please send a PR if you think the default serializer should be improved, instead of jumping to this option.

func WithStripTrailingSlash added in v0.18.7

func WithStripTrailingSlash() func(*Server)

WithStripTrailingSlash ensure all declared routes trailing slash is stripped. This option also applies a middleware that strips the trailing slash from every incoming request.

func WithTemplateFS

func WithTemplateFS(fs fs.FS) func(*Server)

WithTemplateFS sets the filesystem used to load templates. To be used with WithTemplateGlobs or WithTemplates. For example:

WithTemplateFS(os.DirFS("./templates"))

or with embedded templates:

//go:embed templates
var templates embed.FS
...
WithTemplateFS(templates)

func WithTemplateGlobs

func WithTemplateGlobs(patterns ...string) func(*Server)

WithTemplateGlobs loads templates matching the given patterns from the server filesystem. If the server filesystem is not set, it will use the OS filesystem, at folder "./templates". For example:

WithTemplateGlobs("*.html, */*.html", "*/*/*.html")
WithTemplateGlobs("pages/*.html", "pages/admin/*.html")

for reference about the glob patterns in Go (no ** support for example): https://pkg.go.dev/path/filepath?utm_source=godoc#Match

func WithTemplates

func WithTemplates(templates *template.Template) func(*Server)

WithTemplates loads the templates used to render HTML. To be used with WithTemplateFS. If not set, it will use the os filesystem, at folder "./templates".

func WithValidator added in v0.13.0

func WithValidator(newValidator *validator.Validate) func(*Server)

WithValidator sets the validator to be used by the fuego server. If no validator is provided, a default validator will be used.

Note: If you are using the default validator, you can add tags to your structs using the `validate` tag. For example:

type MyStruct struct {
	Field1 string `validate:"required"`
	Field2 int    `validate:"min=10,max=20"`
}

The above struct will be validated using the default validator, and if any errors occur, they will be returned as part of the response.

func WithValue added in v0.10.0

func WithValue(ctx context.Context, val any) context.Context

func WithXML deprecated

func WithXML() func(*Server)

WithXML sets the serializer to XML

Deprecated: fuego supports automatic XML serialization when using the header "Accept: application/xml".

func WithoutAutoGroupTags added in v0.14.0

func WithoutAutoGroupTags() func(*Server)

WithoutAutoGroupTags disables the automatic grouping of routes by tags. By default, routes are tagged by group. For example:

recipeGroup := fuego.Group(s, "/recipes")
fuego.Get(recipeGroup, "/", func(ContextNoBody) (ans, error) {
	return ans{}, nil
})

RecipeThis route will be tagged with "recipes" by default, but with this option, they will not be tagged.

func WithoutLogger

func WithoutLogger() func(*Server)

WithoutLogger disables the default logger.

func WithoutStartupMessages added in v0.14.0

func WithoutStartupMessages() func(*Server)

WithoutStartupMessages disables the startup message

Types

type AutoAuthConfig

type AutoAuthConfig struct {
	VerifyUserInfo func(user, password string) (jwt.Claims, error) // Must check the username and password, and return the claims
	Enabled        bool
}

type BadRequestError

type BadRequestError HTTPError

BadRequestError is an error used to return a 400 status code.

func (BadRequestError) Error

func (e BadRequestError) Error() string

func (BadRequestError) StatusCode added in v0.13.0

func (e BadRequestError) StatusCode() int

func (BadRequestError) Unwrap added in v0.13.0

func (e BadRequestError) Unwrap() error

type BaseRoute added in v0.15.0

type BaseRoute struct {
	// handler executed for this route
	Handler http.Handler

	// OpenAPI operation
	Operation *openapi3.Operation

	// Ref to the whole OpenAPI spec. Be careful when changing directly its value directly.
	OpenAPI *OpenAPI

	Params map[string]OpenAPIParam

	// HTTP method (GET, POST, PUT, PATCH, DELETE)
	Method string

	// URL path. Will be prefixed by the base path of the server and the group path if any
	Path string

	// namespace and name of the function to execute
	FullName string

	// Content types accepted for the request body. If nil, all content types (*/*) are accepted.
	RequestContentTypes []string

	Middlewares []func(http.Handler) http.Handler

	// Default status code for the response
	DefaultStatusCode int

	// If true, the route will not be documented in the OpenAPI spec
	Hidden bool

	// Middleware configuration for the route
	MiddlewareConfig *MiddlewareConfig
	// contains filtered or unexported fields
}

BaseRoute is the base struct for all routes in Fuego. It contains the OpenAPI operation and other metadata.

func NewBaseRoute added in v0.17.0

func NewBaseRoute(method, path string, handler any, e *Engine, options ...func(*BaseRoute)) BaseRoute

func (*BaseRoute) GenerateDefaultDescription added in v0.17.0

func (r *BaseRoute) GenerateDefaultDescription()

func (*BaseRoute) GenerateDefaultOperationID added in v0.17.0

func (r *BaseRoute) GenerateDefaultOperationID()

type ConflictError added in v0.13.0

type ConflictError HTTPError

ConflictError is an error used to return a 409 status code.

func (ConflictError) Error added in v0.13.0

func (e ConflictError) Error() string

func (ConflictError) StatusCode added in v0.13.0

func (e ConflictError) StatusCode() int

func (ConflictError) Unwrap added in v0.13.0

func (e ConflictError) Unwrap() error

type ContextFlowable added in v0.17.0

type ContextFlowable[B any] interface {
	ContextWithBody[B]

	// SetDefaultStatusCode sets the status code of the response defined in the options.
	SetDefaultStatusCode()
	// Serialize serializes the given data to the response.
	Serialize(data any) error
	// SerializeError serializes the given error to the response.
	SerializeError(err error)
}

ContextFlowable contains the logic for the flow of a Fuego controller. Extends ContextWithBody with methods not exposed in the Controllers.

type ContextNoBody added in v0.10.0

type ContextNoBody = ContextWithBody[any]

type ContextWithBody added in v0.10.0

type ContextWithBody[B any] interface {
	context.Context

	ValidableCtx

	// Body returns the body of the request.
	// If (*B) implements [InTransformer], it will be transformed after deserialization.
	// It caches the result, so it can be called multiple times.
	Body() (B, error)

	// MustBody works like Body, but panics if there is an error.
	MustBody() B

	// PathParam returns the path parameter with the given name.
	// If it does not exist, it returns an empty string.
	// Example:
	//   fuego.Get(s, "/recipes/{recipe_id}", func(c fuego.ContextNoBody) (any, error) {
	//	 	id := c.PathParam("recipe_id")
	//   	...
	//   })
	PathParam(name string) string
	// If the path parameter is not provided or is not an int, it returns 0. Use [Ctx.PathParamIntErr] if you want to know if the path parameter is erroneous.
	PathParamInt(name string) int
	PathParamIntErr(name string) (int, error)

	QueryParam(name string) string
	QueryParamArr(name string) []string
	QueryParamInt(name string) int // If the query parameter is not provided or is not an int, it returns the default given value. Use [Ctx.QueryParamIntErr] if you want to know if the query parameter is erroneous.
	QueryParamIntErr(name string) (int, error)
	QueryParamBool(name string) bool // If the query parameter is not provided or is not a bool, it returns the default given value. Use [Ctx.QueryParamBoolErr] if you want to know if the query parameter is erroneous.
	QueryParamBoolErr(name string) (bool, error)
	QueryParams() url.Values

	MainLang() string   // ex: fr. MainLang returns the main language of the request. It is the first language of the Accept-Language header. To get the main locale (ex: fr-CA), use [Ctx.MainLocale].
	MainLocale() string // ex: en-US. MainLocale returns the main locale of the request. It is the first locale of the Accept-Language header. To get the main language (ex: en), use [Ctx.MainLang].

	// Render renders the given templates with the given data.
	// Example:
	//   fuego.Get(s, "/recipes", func(c fuego.ContextNoBody) (any, error) {
	//   	recipes, _ := rs.Queries.GetRecipes(c.Context())
	//   		...
	//   	return c.Render("pages/recipes.page.html", recipes)
	//   })
	// For the Go templates reference, see https://pkg.go.dev/html/template
	//
	// [templateGlobsToOverride] is a list of templates to override.
	// For example, if you have 2 conflicting templates
	//   - with the same name "partials/aaa/nav.partial.html" and "partials/bbb/nav.partial.html"
	//   - or two templates with different names, but that define the same block "page" for example,
	// and you want to override one above the other, you can do:
	//   c.Render("admin.page.html", recipes, "partials/aaa/nav.partial.html")
	// By default, [templateToExecute] is added to the list of templates to override.
	Render(templateToExecute string, data any, templateGlobsToOverride ...string) (CtxRenderer, error)

	Cookie(name string) (*http.Cookie, error) // Get request cookie
	SetCookie(cookie http.Cookie)             // Sets response cookie
	Header(key string) string                 // Get request header
	SetHeader(key, value string)              // Sets response header

	// Returns the underlying net/http, gin or echo context.
	//
	// Usage:
	//  ctx := c.Context() // net/http: the [context.Context] of the *http.Request
	//  ctx := c.Context().(*gin.Context) // gin: Safe because the underlying context is always a [gin.Context]
	//  ctx := c.Context().(echo.Context) // echo: Safe because the underlying context is always a [echo.Context]
	Context() context.Context

	Request() *http.Request        // Request returns the underlying HTTP request.
	Response() http.ResponseWriter // Response returns the underlying HTTP response writer.

	// SetStatus sets the status code of the response.
	// Alias to http.ResponseWriter.WriteHeader.
	SetStatus(code int)

	// Redirect redirects to the given url with the given status code.
	// Example:
	//   fuego.Get(s, "/recipes", func(c fuego.ContextNoBody) (any, error) {
	//   	...
	//   	return c.Redirect(301, "/recipes-list")
	//   })
	Redirect(code int, url string) (any, error)
}

ContextWithBody is the context of the request. It contains the request body, the path parameters, the query parameters, and the HTTP request. Please do not use a pointer type as parameter.

type ContextWithBodyAndParams added in v0.18.0

type ContextWithBodyAndParams[Body any, ParamsIn any, ParamsOut any] interface {
	ContextWithBody[Body]
	Params() (ParamsIn, error)
	SetParams(ParamsOut) error
}

type ContextWithPathParam added in v0.18.0

type ContextWithPathParam interface {
	PathParam(name string) string
}

type CtxRenderer added in v0.9.0

type CtxRenderer interface {
	Render(context.Context, io.Writer) error
}

CtxRenderer is an interface that can be used to render a response. It is used with standard library templating engine, by using fuego.ContextXXX.Render It is compatible with github.com/a-h/templ out of the box. Example:

func getRecipes(ctx fuego.ContextNoBody) (fuego.CtxRenderer, error) {
	recipes, err := ctx.store.GetRecipes(ctx.Context())
	if err != nil {
		return nil, err
	}

	return recipeComponent(recipes), nil // recipeComponent is templ component
}

type DataOrTemplate added in v0.14.0

type DataOrTemplate[T any] struct {
	Data     T
	Template any
}

DataOrTemplate is a struct that can return either data or a template depending on the asked type.

func DataOrHTML added in v0.14.0

func DataOrHTML[T any](data T, template any) *DataOrTemplate[T]

DataOrHTML is a helper function to create a DataOrTemplate return item without specifying the type.

func (DataOrTemplate[T]) MarshalJSON added in v0.14.0

func (m DataOrTemplate[T]) MarshalJSON() ([]byte, error)

func (DataOrTemplate[T]) MarshalXML added in v0.14.0

func (m DataOrTemplate[T]) MarshalXML(e *xml.Encoder, _ xml.StartElement) error

func (DataOrTemplate[T]) MarshalYAML added in v0.14.0

func (m DataOrTemplate[T]) MarshalYAML() (any, error)

func (DataOrTemplate[T]) Render added in v0.14.0

func (m DataOrTemplate[T]) Render(c context.Context, w io.Writer) error

func (DataOrTemplate[T]) String added in v0.14.0

func (m DataOrTemplate[T]) String() string

type Engine added in v0.17.0

type Engine struct {
	OpenAPI      *OpenAPI
	ErrorHandler func(error) error
	// contains filtered or unexported fields
}

The Engine is the main struct of the framework.

func NewEngine added in v0.17.0

func NewEngine(options ...func(*Engine)) *Engine

NewEngine creates a new Engine with the given options. For example:

engine := fuego.NewEngine(
	WithOpenAPIConfig(
		OpenAPIConfig{
			PrettyFormatJSON: true,
		},
	),
)

Options all begin with `With`.

func (*Engine) OutputOpenAPISpec added in v0.18.0

func (e *Engine) OutputOpenAPISpec() *openapi3.T

OutputOpenAPISpec takes the OpenAPI spec and outputs it to a JSON file

func (*Engine) RegisterOpenAPIRoutes added in v0.18.0

func (e *Engine) RegisterOpenAPIRoutes(o OpenAPIServable)

func (*Engine) SpecHandler added in v0.18.0

func (e *Engine) SpecHandler() func(c ContextNoBody) (openapi3.T, error)

type ErrorItem added in v0.13.0

type ErrorItem struct {
	More   map[string]any `json:"more,omitempty" xml:"more,omitempty" description:"Additional information about the error"`
	Name   string         `json:"name" xml:"name" description:"For example, name of the parameter that caused the error"`
	Reason string         `json:"reason" xml:"reason" description:"Human readable error message"`
}

type ErrorSender added in v0.15.0

type ErrorSender = func(http.ResponseWriter, *http.Request, error)

type ErrorWithDetail added in v0.16.2

type ErrorWithDetail interface {
	error
	DetailMsg() string
}

ErrorWithDetail is an interface that can be implemented by an error to provide an additional detail message about the error

type ErrorWithStatus

type ErrorWithStatus interface {
	error
	StatusCode() int
}

ErrorWithStatus is an interface that can be implemented by an error to provide a status code

type ForbiddenError added in v0.13.0

type ForbiddenError HTTPError

ForbiddenError is an error used to return a 403 status code.

func (ForbiddenError) Error added in v0.13.0

func (e ForbiddenError) Error() string

func (ForbiddenError) StatusCode added in v0.13.0

func (e ForbiddenError) StatusCode() int

func (ForbiddenError) Unwrap added in v0.13.0

func (e ForbiddenError) Unwrap() error

type Gomponent added in v0.9.0

type Gomponent = Renderer

Gomponent is a shortcut for Renderer, which can be used with github.com/maragudk/gomponents

type H

type H map[string]any

H is a shortcut for map[string]any

type HTML

type HTML string

HTML is a marker type used to differentiate between a string response and an HTML response. To use templating, use [Context.Render].

type HTTPError

type HTTPError struct {
	// Developer readable error message. Not shown to the user to avoid security leaks.
	Err error `json:"-" xml:"-" yaml:"-"`
	// URL of the error type. Can be used to lookup the error in a documentation
	Type string `` /* 152-byte string literal not displayed */
	// Short title of the error
	Title string `json:"title,omitempty" xml:"title,omitempty" yaml:"title,omitempty" description:"Short title of the error"`
	// HTTP status code. If using a different type than [HTTPError], for example [BadRequestError], this will be automatically overridden after Fuego error handling.
	Status int `json:"status,omitempty" xml:"status,omitempty" yaml:"status,omitempty" description:"HTTP status code" example:"403"`
	// Human readable error message
	Detail   string      `json:"detail,omitempty" xml:"detail,omitempty" yaml:"detail,omitempty" description:"Human readable error message"`
	Instance string      `json:"instance,omitempty" xml:"instance,omitempty" yaml:"instance,omitempty"`
	Errors   []ErrorItem `json:"errors,omitempty" xml:"errors,omitempty" yaml:"errors,omitempty"`
}

HTTPError is the error response used by the serialization part of the framework.

func (HTTPError) DetailMsg added in v0.16.2

func (e HTTPError) DetailMsg() string

func (HTTPError) Error

func (e HTTPError) Error() string

func (HTTPError) PublicError added in v0.18.6

func (e HTTPError) PublicError() string

PublicError returns a human readable error message. It ignores the underlying error for security and only returns the status code, title and detail.

func (HTTPError) StatusCode

func (e HTTPError) StatusCode() int

func (HTTPError) Unwrap added in v0.13.0

func (e HTTPError) Unwrap() error

type InTransformer

type InTransformer interface {
	InTransform(context.Context) error // InTransforms the entity.
}

InTransformer is an interface for entities that can be transformed. Useful for example for trimming strings, changing case, etc. Can also raise an error if the entity is not valid.

type InternalServerError added in v0.15.0

type InternalServerError = HTTPError

InternalServerError is an error used to return a 500 status code.

type LoggingConfig added in v0.18.0

type LoggingConfig struct {
	// Optional custom request ID generator
	RequestIDFunc func() string
	// If true, request logging is disabled
	DisableRequest bool
	// If true, response logging is disabled
	DisableResponse bool
}

LoggingConfig is the configuration for the default logging middleware

It allows for request and response logging to be disabled independently, and for a custom request ID generator to be used

For example:

config := fuego.LoggingConfig{
	    DisableRequest:  true,
	    RequestIDFunc: func() string {
	        return fmt.Sprintf("custom-%d", time.Now().UnixNano())
	    },
	}

The above configuration will disable the debug request logging and override the default request ID generator (UUID) with a custom one that appends the current Unix time in nanoseconds for response logs

func (*LoggingConfig) Disabled added in v0.18.0

func (l *LoggingConfig) Disabled() bool

type LoginPayload

type LoginPayload struct {
	User     string `json:"user" validate:"required"` // Might be an email, a username, or anything else that identifies uniquely the user
	Password string `json:"password" validate:"required"`
}

type MiddlewareConfig added in v0.18.1

type MiddlewareConfig struct {
	DisableMiddlewareSection bool
	MaxNumberOfMiddlewares   int
	ShortMiddlewaresPaths    bool
}

type MockContext added in v0.18.0

type MockContext[B any] struct {
	internal.CommonContext[B]

	RequestBody B
	Headers     http.Header
	PathParams  map[string]string

	Cookies map[string]*http.Cookie
	// contains filtered or unexported fields
}

MockContext provides a framework-agnostic implementation of ContextWithBody for testing purposes. It allows testing controllers without depending on specific web frameworks like Gin or Echo.

func NewMockContext added in v0.18.0

func NewMockContext[B any](body B) *MockContext[B]

NewMockContext creates a new MockContext instance with the provided body

func NewMockContextNoBody added in v0.18.0

func NewMockContextNoBody() *MockContext[any]

NewMockContextNoBody creates a new MockContext suitable for a request & controller with no body

func (*MockContext[B]) Body added in v0.18.0

func (m *MockContext[B]) Body() (B, error)

Body returns the previously set body value

func (*MockContext[B]) Cookie added in v0.18.0

func (m *MockContext[B]) Cookie(name string) (*http.Cookie, error)

Cookie returns a mock cookie

func (*MockContext[B]) HasCookie added in v0.18.0

func (m *MockContext[B]) HasCookie(key string) bool

HasCookie checks if a cookie exists

func (*MockContext[B]) HasHeader added in v0.18.0

func (m *MockContext[B]) HasHeader(key string) bool

HasHeader checks if a header exists

func (*MockContext[B]) Header added in v0.18.0

func (m *MockContext[B]) Header(key string) string

Header returns the value of the specified header

func (*MockContext[B]) MainLang added in v0.18.0

func (m *MockContext[B]) MainLang() string

MainLang returns the main language from Accept-Language header

func (*MockContext[B]) MainLocale added in v0.18.0

func (m *MockContext[B]) MainLocale() string

MainLocale returns the main locale from Accept-Language header

func (*MockContext[B]) MustBody added in v0.18.0

func (m *MockContext[B]) MustBody() B

MustBody returns the body or panics if there's an error

func (*MockContext[B]) PathParam added in v0.18.0

func (m *MockContext[B]) PathParam(name string) string

PathParam returns a mock path parameter

func (*MockContext[B]) PathParamInt added in v0.18.0

func (m *MockContext[B]) PathParamInt(name string) int

func (*MockContext[B]) PathParamIntErr added in v0.18.0

func (m *MockContext[B]) PathParamIntErr(name string) (int, error)

func (*MockContext[B]) Redirect added in v0.18.0

func (m *MockContext[B]) Redirect(code int, url string) (any, error)

Redirect returns a redirect response

func (*MockContext[B]) Render added in v0.18.0

func (m *MockContext[B]) Render(templateToExecute string, data any, templateGlobsToOverride ...string) (CtxRenderer, error)

Render is a mock implementation that does nothing

func (*MockContext[B]) Request added in v0.18.0

func (m *MockContext[B]) Request() *http.Request

Request returns the mock request

func (*MockContext[B]) Response added in v0.18.0

func (m *MockContext[B]) Response() http.ResponseWriter

Response returns the mock response writer

func (*MockContext[B]) SetCookie added in v0.18.0

func (m *MockContext[B]) SetCookie(cookie http.Cookie)

SetCookie sets a cookie in the mock context

func (*MockContext[B]) SetHeader added in v0.18.0

func (m *MockContext[B]) SetHeader(key, value string)

SetHeader sets a header in the mock context

func (*MockContext[B]) SetQueryParam added in v0.18.0

func (m *MockContext[B]) SetQueryParam(name, value string) *MockContext[B]

SetQueryParam adds a query parameter to the mock context with OpenAPI validation

func (*MockContext[B]) SetQueryParamBool added in v0.18.0

func (m *MockContext[B]) SetQueryParamBool(name string, value bool) *MockContext[B]

SetQueryParamBool adds a boolean query parameter to the mock context with OpenAPI validation

func (*MockContext[B]) SetQueryParamInt added in v0.18.0

func (m *MockContext[B]) SetQueryParamInt(name string, value int) *MockContext[B]

SetQueryParamInt adds an integer query parameter to the mock context with OpenAPI validation

func (*MockContext[B]) SetStatus added in v0.18.0

func (m *MockContext[B]) SetStatus(code int)

SetStatus sets the response status code

type NotAcceptableError added in v0.15.0

type NotAcceptableError HTTPError

NotAcceptableError is an error used to return a 406 status code.

func (NotAcceptableError) Error added in v0.15.0

func (e NotAcceptableError) Error() string

func (NotAcceptableError) StatusCode added in v0.15.0

func (e NotAcceptableError) StatusCode() int

func (NotAcceptableError) Unwrap added in v0.15.0

func (e NotAcceptableError) Unwrap() error

type NotFoundError added in v0.13.0

type NotFoundError HTTPError

NotFoundError is an error used to return a 404 status code.

func (NotFoundError) Error added in v0.13.0

func (e NotFoundError) Error() string

func (NotFoundError) StatusCode added in v0.13.0

func (e NotFoundError) StatusCode() int

func (NotFoundError) Unwrap added in v0.13.0

func (e NotFoundError) Unwrap() error

type OpenAPI added in v0.16.2

type OpenAPI struct {
	Config OpenAPIConfig
	// contains filtered or unexported fields
}

OpenAPI holds the OpenAPI OpenAPIDescription (OAD) and OpenAPI capabilities.

func NewOpenAPI added in v0.16.2

func NewOpenAPI() *OpenAPI

func (*OpenAPI) Description added in v0.16.2

func (openAPI *OpenAPI) Description() *openapi3.T

func (*OpenAPI) Generator added in v0.16.2

func (openAPI *OpenAPI) Generator() *openapi3gen.Generator

type OpenAPIConfig added in v0.13.0

type OpenAPIConfig struct {
	// Local path to save the OpenAPI JSON spec
	JSONFilePath string
	// If true, the server will not serve nor generate any OpenAPI resources
	Disabled bool
	// If true, the engine will not print messages
	DisableMessages bool
	// If true, the engine will not save the OpenAPI JSON spec locally
	DisableLocalSave bool
	// If true, no default server will be added.
	// Note: this option only applies to the fuego [Server]. Adaptors are not affected by this option.
	DisableDefaultServer bool
	// Pretty prints the OpenAPI spec with proper JSON indentation
	PrettyFormatJSON bool
	// URL to serve the OpenAPI JSON spec
	SpecURL string
	// Handler to serve the OpenAPI UI from spec URL
	UIHandler func(specURL string) http.Handler
	// URL to serve the swagger UI
	SwaggerURL string
	// If true, the server will not serve the Swagger UI
	DisableSwaggerUI bool
	// Middleware configuration for the engine
	MiddlewareConfig MiddlewareConfig
}

type OpenAPIDescriptioner added in v0.14.0

type OpenAPIDescriptioner interface {
	Description() string
}

type OpenAPIParam added in v0.11.0

type OpenAPIParam = internal.OpenAPIParam

type OpenAPIServable added in v0.18.0

type OpenAPIServable interface {
	SpecHandler(e *Engine)
	UIHandler(e *Engine)
}

type OutTransformer

type OutTransformer interface {
	OutTransform(context.Context) error // Transforms an entity before sending it.
}

OutTransformer is an interface for entities that can be transformed. Useful for example for trimming strings, changing case, etc. Can also raise an error if the entity is not valid. Must be implemented by a POINTER RECEIVER. Example:

type User struct {
	Name     string `json:"name"`
	Password string `json:"password"`
}

// Not (u User) but (u *User)

func (u *User) OutTransform(context.Context) error {
	u.Name = "M. " + u.Name
	u.Password = "*****"
	return nil
}

type ParamType added in v0.15.0

type ParamType = internal.ParamType // Query, Header, Cookie
const (
	PathParamType   ParamType = "path"
	QueryParamType  ParamType = "query"
	HeaderParamType ParamType = "header"
	CookieParamType ParamType = "cookie"
)

type PathParamInvalidTypeError added in v0.18.0

type PathParamInvalidTypeError struct {
	Err          error
	ParamName    string
	ParamValue   string
	ExpectedType string
}

func (PathParamInvalidTypeError) Error added in v0.18.0

func (PathParamInvalidTypeError) StatusCode added in v0.18.0

func (e PathParamInvalidTypeError) StatusCode() int

type PathParamNotFoundError added in v0.18.0

type PathParamNotFoundError struct {
	ParamName string
}

func (PathParamNotFoundError) Error added in v0.18.0

func (e PathParamNotFoundError) Error() string

func (PathParamNotFoundError) StatusCode added in v0.18.0

func (e PathParamNotFoundError) StatusCode() int

type Registerer added in v0.18.0

type Registerer[T, B any] interface {
	Register() Route[T, B]
}

Registerer is an interface that allows registering routes. It can be implementable by any router.

type Renderer added in v0.9.0

type Renderer interface {
	Render(io.Writer) error
}

Renderer can be used with github.com/maragudk/gomponents Example:

func getRecipes(ctx fuego.ContextNoBody) (fuego.CtxRenderer, error) {
	recipes, err := ctx.store.GetRecipes(ctx.Context())
	if err != nil {
		return nil, err
	}

	return recipeComponent(recipes), nil // recipeComponent is gomponents component
}

type RequestBody added in v0.18.7

type RequestBody struct {
	// user provided type
	Type any
	// content-type of the request i.e application/json
	ContentTypes []string
}

RequestBody represents a fuego.RequestBody that can be used when setting custom request type on routes

type Response added in v0.17.0

type Response struct {
	// user provided type
	Type any
	// content-type of the response i.e application/json
	ContentTypes []string
}

Response represents a fuego.Response that can be used when setting custom response types on routes

type Route

type Route[ResponseBody any, RequestBody any] struct {
	BaseRoute
}

Route is the main struct for a route in Fuego. It contains the OpenAPI operation and other metadata. It is a wrapper around BaseRoute, with the addition of the response and request body types.

func All

func All[T, B any](s *Server, path string, controller func(ContextWithBody[B]) (T, error), options ...func(*BaseRoute)) *Route[T, B]

All captures all methods (GET, POST, PUT, PATCH, DELETE) and register a controller.

func AllStd added in v0.14.0

func AllStd(s *Server, path string, controller func(http.ResponseWriter, *http.Request), options ...func(*BaseRoute)) *Route[any, any]

func Delete

func Delete[T, B any](s *Server, path string, controller func(ContextWithBody[B]) (T, error), options ...func(*BaseRoute)) *Route[T, B]

func DeleteStd

func DeleteStd(s *Server, path string, controller func(http.ResponseWriter, *http.Request), options ...func(*BaseRoute)) *Route[any, any]

func Get

func Get[T, B any](s *Server, path string, controller func(ContextWithBody[B]) (T, error), options ...func(*BaseRoute)) *Route[T, B]

func GetStd

func GetStd(s *Server, path string, controller func(http.ResponseWriter, *http.Request), options ...func(*BaseRoute)) *Route[any, any]

func Handle

func Handle(s *Server, path string, controller http.Handler, options ...func(*BaseRoute)) *Route[any, any]

Handle registers a standard HTTP handler into the default mux. Use this function if you want to use a standard HTTP handler instead of a Fuego controller.

func NewRoute added in v0.17.0

func NewRoute[T, B any](method, path string, handler any, e *Engine, options ...func(*BaseRoute)) Route[T, B]

func Options added in v0.18.5

func Options[T, B any](s *Server, path string, controller func(ContextWithBody[B]) (T, error), options ...func(*BaseRoute)) *Route[T, B]

func OptionsStd added in v0.18.5

func OptionsStd(s *Server, path string, controller func(http.ResponseWriter, *http.Request), options ...func(*BaseRoute)) *Route[any, any]

func Patch

func Patch[T, B any](s *Server, path string, controller func(ContextWithBody[B]) (T, error), options ...func(*BaseRoute)) *Route[T, B]

func PatchStd

func PatchStd(s *Server, path string, controller func(http.ResponseWriter, *http.Request), options ...func(*BaseRoute)) *Route[any, any]

func Post

func Post[T, B any](s *Server, path string, controller func(ContextWithBody[B]) (T, error), options ...func(*BaseRoute)) *Route[T, B]

func PostStd

func PostStd(s *Server, path string, controller func(http.ResponseWriter, *http.Request), options ...func(*BaseRoute)) *Route[any, any]

func Put

func Put[T, B any](s *Server, path string, controller func(ContextWithBody[B]) (T, error), options ...func(*BaseRoute)) *Route[T, B]

func PutStd

func PutStd(s *Server, path string, controller func(http.ResponseWriter, *http.Request), options ...func(*BaseRoute)) *Route[any, any]

func Register deprecated

func Register[T, B any](s *Server, route Route[T, B], controller http.Handler, options ...func(*BaseRoute)) *Route[T, B]

Register registers a controller into the default net/http mux.

Deprecated: Used internally. Please satisfy the Registerer interface instead and pass to Registers.

func Registers added in v0.18.0

func Registers[B, T any](engine *Engine, a Registerer[B, T]) *Route[B, T]

func (Route[T, B]) NameFromNamespace added in v0.14.0

func (route Route[T, B]) NameFromNamespace(opts ...func(string) string) string

NameFromNamespace returns the Route's FullName final string delimited by `.`. Essentially getting the name of the function and leaving the package path

The output can be further modified with a list of optional string manipulation funcs (i.e func(string) string)

func (*Route[ResponseBody, RequestBody]) RegisterOpenAPIOperation added in v0.16.2

func (route *Route[ResponseBody, RequestBody]) RegisterOpenAPIOperation(openapi *OpenAPI) error

RegisterOpenAPIOperation registers the route to the OpenAPI description. Modifies the route's Operation.

type RouteWithParams added in v0.18.0

type RouteWithParams[RequestParams any, ResponseBody any, RequestBody any] struct {
	Route[ResponseBody, RequestBody]
}

func NewRouteWithParams added in v0.18.0

func NewRouteWithParams[RequestParams, ResponseBody, RequestBody any](method, path string, handler any, e *Engine, options ...func(*BaseRoute)) RouteWithParams[RequestParams, ResponseBody, RequestBody]

func (*RouteWithParams[Params, ResponseBody, RequestBody]) RegisterParams added in v0.18.0

func (route *RouteWithParams[Params, ResponseBody, RequestBody]) RegisterParams() error

RegisterParams registers the parameters of a given type to an OpenAPI operation. It inspects the fields of the provided struct, looking for "header" tags, and creates OpenAPI parameters for each tagged field.

type SchemaTag added in v0.15.0

type SchemaTag struct {
	openapi3.SchemaRef
	Name string
}

SchemaTag is a struct that holds the name of the struct and the associated openapi3.SchemaRef

func SchemaTagFromType added in v0.15.0

func SchemaTagFromType(openapi *OpenAPI, v any) SchemaTag

type Security

type Security struct {
	Now             func() time.Time
	ExpiresInterval time.Duration
	// contains filtered or unexported fields
}

Security holds the key to sign the JWT tokens, and configuration information. The key isn't accessible once created to avoid leaking it. To use it, please use the methods provided.

func NewSecurity

func NewSecurity() Security

func (Security) CookieLogoutHandler

func (security Security) CookieLogoutHandler(w http.ResponseWriter, r *http.Request)

CookieLogoutHandler generates a JWT token with the given claims and writes it to the cookies. Usage:

fuego.PostStd(s, "/auth/logout", security.CookieLogoutHandler)

Dependency to Security is for symmetry with [RefreshHandler].

func (Security) GenerateToken

func (security Security) GenerateToken(claims jwt.Claims) (token string, err error)

GenerateToken generates a JWT token with the given claims. The claims must be a jwt.MapClaims or embed jwt.RegisteredClaims.

func (Security) GenerateTokenToCookies

func (security Security) GenerateTokenToCookies(claims jwt.Claims, w http.ResponseWriter) (string, error)

GenerateTokenToCookies generates a JWT token with the given claims and writes it to the cookies.

func (Security) LoginHandler

func (security Security) LoginHandler(verifyUserInfo func(user, password string) (jwt.Claims, error)) func(ContextWithBody[LoginPayload]) (tokenResponse, error)

LoginHandler is a premade login handler. It takes a function that checks if the user is authorized. Example:

security := fuego.NewSecurity()
security.ExpiresInterval = 24 * time.Hour
fuego.Post(s, "/login", security.LoginHandler(verifyUserInfo))
...
func verifyUserInfo(r *http.Request) (jwt.Claims, error) {
	// Get the username and password from the request
	username := r.FormValue("username")
	password := r.FormValue("password")
	// ...
	// Check if the username and password are correct.
	// Usually, you would check in a database.
	if username != "myUsername" || password != "myPassword" {
		return nil, errors.New("invalid username or password")
	}
	// ...
	// Return the claims
	return &MyCustomToken{
		It is recommended to embed jwt.RegisteredClaims in your custom struct that will define your JWT.
		RegisteredClaims: jwt.RegisteredClaims{
			Issuer:    username,
			Subject:   username,
			Audience:  jwt.ClaimStrings{"aud1", "aud2"},
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(24 * time.Hour)),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			ID:        "1234567890",
		},
		Username: "myUsername",
	}, nil

func (Security) RefreshHandler

func (security Security) RefreshHandler(w http.ResponseWriter, r *http.Request)

RefreshHandler is a premade refresh handler. It refreshes the token with the same information as the previous one, but with a new issued date. It sends the new token to the cookies and to the response. Usage:

fuego.PostStd(s, "/auth/refresh", security.RefreshHandler)

func (Security) StdLoginHandler

func (security Security) StdLoginHandler(verifyUserInfo func(r *http.Request) (jwt.Claims, error)) func(w http.ResponseWriter, r *http.Request)

StdLoginHandler is a premade login handler. It takes a function that checks if the user is authorized. Example:

security := fuego.NewSecurity()
security.ExpiresInterval = 24 * time.Hour
fuego.Post(s, "/login", security.StdLoginHandler(verifyUserInfo))
...
func verifyUserInfo(r *http.Request) (jwt.Claims, error) {
	// Get the username and password from the request
	username := r.FormValue("username")
	password := r.FormValue("password")
	// ...
	// Check if the username and password are correct.
	// Usually, you would check in a database.
	if username != "myUsername" || password != "myPassword" {
		return nil, errors.New("invalid username or password")
	}
	// ...
	// Return the claims
	return &MyCustomToken{
		It is recommended to embed jwt.RegisteredClaims in your custom struct that will define your JWT.
		RegisteredClaims: jwt.RegisteredClaims{
			Issuer:    username,
			Subject:   username,
			Audience:  jwt.ClaimStrings{"aud1", "aud2"},
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(24 * time.Hour)),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			ID:        "1234567890",
		},
		Username: "myUsername",
	}, nil

func (Security) TokenToContext

func (security Security) TokenToContext(searchFunc ...func(*http.Request) string) func(next http.Handler) http.Handler

TokenToContext is a middleware that checks if the user is authenticated from various authentication methods. Once found, the token is parsed, validated and the claims are set in the context. TLDR: after this middleware, the token is either non-existent or validated. You can use TokenFromContext to get the claims

func (Security) ValidateToken

func (security Security) ValidateToken(token string) (*jwt.Token, error)

type Sender added in v0.15.0

type Sender func(http.ResponseWriter, *http.Request, any) error

type Server

type Server struct {
	// The underlying HTTP server
	*http.Server

	// Will be plugged into the Server field.
	// Not using directly the Server field so
	// [http.ServeMux.Handle] can also be used to register routes.
	Mux *http.ServeMux

	*Engine

	// Custom serializer that overrides the default one.
	Serialize Sender
	// Used to serialize the error response. Defaults to [SendError].
	SerializeError ErrorSender

	Security Security

	// If true, the server will return an error if the request body contains unknown fields. Useful for quick debugging in development.
	DisallowUnknownFields bool
	// contains filtered or unexported fields
}

func Group

func Group(s *Server, path string, routeOptions ...func(*BaseRoute)) *Server

Group allows grouping routes under a common path. Middlewares are scoped to the group. For example:

s := fuego.NewServer()
viewsRoutes := fuego.Group(s, "")
apiRoutes := fuego.Group(s, "/api")
// Registering a middlewares scoped to /api only
fuego.Use(apiRoutes, myMiddleware)
// Registering a route under /api/users
fuego.Get(apiRoutes, "/users", func(c fuego.ContextNoBody) (ans, error) {
	return ans{Ans: "users"}, nil
})
s.Run()

func NewServer

func NewServer(options ...func(*Server)) *Server

NewServer creates a new server with the given options. Fuego's Server is built on top of the standard library's http.Server. The OpenAPI and data flow is handled by the Engine, a lightweight abstraction available for all kind of routers (net/http, Gin, Echo). For example:

app := fuego.NewServer(
	fuego.WithAddr(":8080"),
	fuego.WithoutLogger(),
)

Options all begin with `With`. Some options are at engine level, and can be set with WithEngineOptions. Some default options are set in the function body.

func (*Server) Hide added in v0.13.0

func (s *Server) Hide() *Server

Hide prevents the routes in this server or group from being included in the OpenAPI spec. Deprecated: Please use OptionHide with WithRouteOptions

func (*Server) Run

func (s *Server) Run() error

Run starts the server. It is blocking. It returns an error if the server could not start (it could not bind to the port for example). It also generates the OpenAPI spec and outputs it to a file, the UI, and a handler (if enabled).

func (*Server) RunTLS added in v0.14.0

func (s *Server) RunTLS(certFile, keyFile string) error

RunTLS starts the server with a TLS listener It is blocking. It returns an error if the server could not start (it could not bind to the port for example). It also generates the OpenAPI spec and outputs it to a file, the UI, and a handler (if enabled).

func (*Server) Show added in v0.13.0

func (s *Server) Show() *Server

Show allows displaying the routes. Activated by default so useless in most cases, but this can be useful if you deactivated the parent group. Deprecated: Please use OptionShow with WithRouteOptions

func (*Server) SpecHandler added in v0.18.0

func (s *Server) SpecHandler(_ *Engine)

func (*Server) UIHandler added in v0.18.0

func (s *Server) UIHandler(_ *Engine)

type StdRenderer added in v0.14.0

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

StdRenderer renders a template using the standard library templating engine.

func (StdRenderer) Render added in v0.14.0

func (s StdRenderer) Render(ctx context.Context, w io.Writer) error

type Templ added in v0.9.0

type Templ = CtxRenderer

Templ is a shortcut for CtxRenderer, which can be used with github.com/a-h/templ

type Timing added in v0.10.0

type Timing struct {
	Name string
	Desc string
	Dur  time.Duration
}

Timing is a struct to represent a server timing. Used in the Server-Timing header.

func (Timing) String added in v0.10.0

func (t Timing) String() string

String returns a string representation of a Timing, as defined in https://www.w3.org/TR/server-timing/#the-server-timing-header-field

type UnauthorizedError added in v0.13.0

type UnauthorizedError HTTPError

UnauthorizedError is an error used to return a 401 status code.

func (UnauthorizedError) Error added in v0.13.0

func (e UnauthorizedError) Error() string

func (UnauthorizedError) StatusCode added in v0.13.0

func (e UnauthorizedError) StatusCode() int

func (UnauthorizedError) Unwrap added in v0.13.0

func (e UnauthorizedError) Unwrap() error

type ValidableCtx added in v0.17.0

type ValidableCtx interface {
	GetOpenAPIParams() map[string]OpenAPIParam
	HasQueryParam(key string) bool
	HasHeader(key string) bool
	HasCookie(key string) bool
}

Directories

Path Synopsis
cmd
fuego Module
examples
acme-tls Module
basic Module
crud-gorm Module
custom-errors Module
gin-compat Module
hello-world Module
openapi Module
petstore Module
extra
sql
Package sql provides error handling for SQL operations.
Package sql provides error handling for SQL operations.
sqlite3
Package sqlite3 provides error handling for SQLite3 database operations.
Package sqlite3 provides error handling for SQLite3 database operations.
fuegoecho Module
fuegogin Module
markdown Module
Package internal provides a common context for all adaptors (net/http, gin, echo, etc...) It is used to share common functionality between all adaptors.
Package internal provides a common context for all adaptors (net/http, gin, echo, etc...) It is used to share common functionality between all adaptors.
middleware
basicauth Module
cache Module
Package option provides a set of shortcuts to configure routes in Fuego.
Package option provides a set of shortcuts to configure routes in Fuego.
Package param provides a set of shortcuts to define parameters for the route Options.
Package param provides a set of shortcuts to define parameters for the route Options.
Package static provides embedded static files for the Fuego framework.
Package static provides embedded static files for the Fuego framework.

Jump to

Keyboard shortcuts

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