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
- Variables
- func AuthWall(authorizedRoles ...string) func(next http.Handler) http.Handler
- func AuthWallRegex(acceptedRolesRegex string) func(next http.Handler) http.Handler
- func AuthWallRegexp(acceptedRolesRegex *regexp.Regexp) func(next http.Handler) http.Handler
- func DefaultDescription[T any](handler string, middlewares []T, middlewareConfig *MiddlewareConfig) string
- func DefaultOpenAPIHTML(specURL string) string
- func DefaultOpenAPIHandler(specURL string) http.Handler
- func DisableErrorHandler() func(*Engine)
- func ErrorHandler(err error) error
- func Flow[B, T any](s *Engine, ctx ContextFlowable[B], ...)
- func FuncName(f any) string
- func GetToken[T any](ctx context.Context) (T, error)
- func GroupOptions(options ...func(*BaseRoute)) func(*BaseRoute)
- func HTTPHandler[ReturnType, Body any](s *Server, controller func(c ContextWithBody[Body]) (ReturnType, error), ...) http.HandlerFunc
- func HandleHTTPError(err error) error
- func InferAcceptHeaderFromType(ans any) string
- func NewNetHTTPContext[B any](route BaseRoute, w http.ResponseWriter, r *http.Request, options readOptions) *netHttpContext[B]
- func NewOpenApiSpec() openapi3.T
- func OptionAddDescription(description string) func(*BaseRoute)
- func OptionAddError(code int, description string, errorType ...any) func(*BaseRoute)
- func OptionAddResponse(code int, description string, response Response) func(*BaseRoute)
- func OptionCookie(name, description string, options ...func(*OpenAPIParam)) func(*BaseRoute)
- func OptionDefaultResponse(description string, response Response) func(*BaseRoute)
- func OptionDefaultStatusCode(defaultStatusCode int) func(*BaseRoute)
- func OptionDeprecated() func(*BaseRoute)
- func OptionDescription(description string) func(*BaseRoute)
- func OptionHeader(name, description string, options ...func(*OpenAPIParam)) func(*BaseRoute)
- func OptionHide() func(*BaseRoute)
- func OptionMiddleware(middleware ...func(http.Handler) http.Handler) func(*BaseRoute)
- func OptionOperationID(operationID string) func(*BaseRoute)
- func OptionOverrideDescription(description string) func(*BaseRoute)
- func OptionParam(name string, options ...func(*OpenAPIParam)) func(*BaseRoute)
- func OptionPath(name, description string, options ...func(*OpenAPIParam)) func(*BaseRoute)
- func OptionQuery(name, description string, options ...func(*OpenAPIParam)) func(*BaseRoute)
- func OptionQueryBool(name, description string, options ...func(*OpenAPIParam)) func(*BaseRoute)
- func OptionQueryInt(name, description string, options ...func(*OpenAPIParam)) func(*BaseRoute)
- func OptionRequestBody(requestBody RequestBody) func(*BaseRoute)
- func OptionRequestContentType(consumes ...string) func(*BaseRoute)
- func OptionResponseHeader(name, description string, options ...func(*OpenAPIParam)) func(*BaseRoute)
- func OptionSecurity(securityRequirements ...openapi3.SecurityRequirement) func(*BaseRoute)
- func OptionShow() func(*BaseRoute)
- func OptionStripTrailingSlash() func(*BaseRoute)
- func OptionSummary(summary string) func(*BaseRoute)
- func OptionTags(tags ...string) func(*BaseRoute)
- func ParamBool() func(param *OpenAPIParam)
- func ParamDefault(value any) func(param *OpenAPIParam)
- func ParamDescription(description string) func(param *OpenAPIParam)
- func ParamExample(exampleName string, value any) func(param *OpenAPIParam)
- func ParamInteger() func(param *OpenAPIParam)
- func ParamNullable() func(param *OpenAPIParam)
- func ParamRequired() func(param *OpenAPIParam)
- func ParamStatusCodes(codes ...int) func(param *OpenAPIParam)
- func ParamString() func(param *OpenAPIParam)
- func PathParamIntErr(c ContextWithPathParam, name string) (int, error)
- func ReadJSON[B any](context context.Context, input io.Reader) (B, error)
- func ReadString[B ~string](context context.Context, input io.Reader) (B, error)
- func ReadURLEncoded[B any](r *http.Request) (B, error)
- func ReadXML[B any](context context.Context, input io.Reader) (B, error)
- func ReadYAML[B any](context context.Context, input io.Reader) (B, error)
- func RegisterOpenAPIOperation[T, B any](openapi *OpenAPI, route Route[T, B]) (*openapi3.Operation, error)deprecated
- func Send(w http.ResponseWriter, r *http.Request, ans any) (err error)
- func SendHTMLError(w http.ResponseWriter, _ *http.Request, err error)
- func SendJSONError(w http.ResponseWriter, _ *http.Request, err error)
- func SendText(w http.ResponseWriter, _ *http.Request, ans any) error
- func SendTextError(w http.ResponseWriter, _ *http.Request, err error)
- func SendXMLError(w http.ResponseWriter, _ *http.Request, err error)
- func SendYAMLError(w http.ResponseWriter, _ *http.Request, err error)
- func TokenFromContext(ctx context.Context) (jwt.Claims, error)
- func TokenFromCookie(r *http.Request) string
- func TokenFromHeader(r *http.Request) string
- func TokenFromQueryParam(r *http.Request) string
- func TransformAndValidate[B any](context context.Context, body B) (B, error)
- func Use(s *Server, middlewares ...func(http.Handler) http.Handler)
- func UseStd(s *Server, middlewares ...func(http.Handler) http.Handler)
- func ValidateParams(c ValidableCtx) error
- func WithAddr(addr string) func(*Server)
- func WithAutoAuth(verifyUserInfo func(user, password string) (jwt.Claims, error)) func(*Server)
- func WithBasePath(basePath string) func(*Server)
- func WithCorsMiddleware(corsMiddleware func(http.Handler) http.Handler) func(*Server)deprecated
- func WithDisallowUnknownFields(b bool) func(*Server)
- func WithEngineOptions(options ...func(*Engine)) func(*Server)
- func WithErrorHandler(errorHandler func(err error) error) func(*Engine)
- func WithErrorSerializer(serializer ErrorSender) func(*Server)
- func WithGlobalMiddlewares(middlewares ...func(http.Handler) http.Handler) func(*Server)
- func WithGlobalResponseTypes(code int, description string, response Response) func(*Server)deprecated
- func WithListener(listener net.Listener) func(*Server)
- func WithLogHandler(handler slog.Handler) func(*Server)
- func WithLoggingMiddleware(loggingConfig LoggingConfig) func(*Server)
- func WithMaxBodySize(maxBodySize int64) func(*Server)
- func WithMiddlewareConfig(cfg MiddlewareConfig) func(*Engine)
- func WithOpenAPIConfig(config OpenAPIConfig) func(*Engine)
- func WithRequestContentType(consumes ...string) func(*Engine)
- func WithRouteOptions(options ...func(*BaseRoute)) func(*Server)
- func WithSecurity(schemes openapi3.SecuritySchemes) func(*Server)
- func WithSerializer(serializer Sender) func(*Server)
- func WithStripTrailingSlash() func(*Server)
- func WithTemplateFS(fs fs.FS) func(*Server)
- func WithTemplateGlobs(patterns ...string) func(*Server)
- func WithTemplates(templates *template.Template) func(*Server)
- func WithValidator(newValidator *validator.Validate) func(*Server)
- func WithValue(ctx context.Context, val any) context.Context
- func WithXML() func(*Server)deprecated
- func WithoutAutoGroupTags() func(*Server)
- func WithoutLogger() func(*Server)
- func WithoutStartupMessages() func(*Server)
- type AutoAuthConfig
- type BadRequestError
- type BaseRoute
- type ConflictError
- type ContextFlowable
- type ContextNoBody
- type ContextWithBody
- type ContextWithBodyAndParams
- type ContextWithPathParam
- type CtxRenderer
- type DataOrTemplate
- func (m DataOrTemplate[T]) MarshalJSON() ([]byte, error)
- func (m DataOrTemplate[T]) MarshalXML(e *xml.Encoder, _ xml.StartElement) error
- func (m DataOrTemplate[T]) MarshalYAML() (any, error)
- func (m DataOrTemplate[T]) Render(c context.Context, w io.Writer) error
- func (m DataOrTemplate[T]) String() string
- type Engine
- type ErrorItem
- type ErrorSender
- type ErrorWithDetail
- type ErrorWithStatus
- type ForbiddenError
- type Gomponent
- type H
- type HTML
- type HTTPError
- type InTransformer
- type InternalServerError
- type LoggingConfig
- type LoginPayload
- type MiddlewareConfig
- type MockContext
- func (m *MockContext[B]) Body() (B, error)
- func (m *MockContext[B]) Cookie(name string) (*http.Cookie, error)
- func (m *MockContext[B]) HasCookie(key string) bool
- func (m *MockContext[B]) HasHeader(key string) bool
- func (m *MockContext[B]) Header(key string) string
- func (m *MockContext[B]) MainLang() string
- func (m *MockContext[B]) MainLocale() string
- func (m *MockContext[B]) MustBody() B
- func (m *MockContext[B]) PathParam(name string) string
- func (m *MockContext[B]) PathParamInt(name string) int
- func (m *MockContext[B]) PathParamIntErr(name string) (int, error)
- func (m *MockContext[B]) Redirect(code int, url string) (any, error)
- func (m *MockContext[B]) Render(templateToExecute string, data any, templateGlobsToOverride ...string) (CtxRenderer, error)
- func (m *MockContext[B]) Request() *http.Request
- func (m *MockContext[B]) Response() http.ResponseWriter
- func (m *MockContext[B]) SetCookie(cookie http.Cookie)
- func (m *MockContext[B]) SetHeader(key, value string)
- func (m *MockContext[B]) SetQueryParam(name, value string) *MockContext[B]
- func (m *MockContext[B]) SetQueryParamBool(name string, value bool) *MockContext[B]
- func (m *MockContext[B]) SetQueryParamInt(name string, value int) *MockContext[B]
- func (m *MockContext[B]) SetStatus(code int)
- type NotAcceptableError
- type NotFoundError
- type OpenAPI
- type OpenAPIConfig
- type OpenAPIDescriptioner
- type OpenAPIParam
- type OpenAPIServable
- type OutTransformer
- type ParamType
- type PathParamInvalidTypeError
- type PathParamNotFoundError
- type Registerer
- type Renderer
- type RequestBody
- type Response
- type Route
- func All[T, B any](s *Server, path string, controller func(ContextWithBody[B]) (T, error), ...) *Route[T, B]
- func AllStd(s *Server, path string, controller func(http.ResponseWriter, *http.Request), ...) *Route[any, any]
- func Delete[T, B any](s *Server, path string, controller func(ContextWithBody[B]) (T, error), ...) *Route[T, B]
- func DeleteStd(s *Server, path string, controller func(http.ResponseWriter, *http.Request), ...) *Route[any, any]
- func Get[T, B any](s *Server, path string, controller func(ContextWithBody[B]) (T, error), ...) *Route[T, B]
- func GetStd(s *Server, path string, controller func(http.ResponseWriter, *http.Request), ...) *Route[any, any]
- func Handle(s *Server, path string, controller http.Handler, options ...func(*BaseRoute)) *Route[any, any]
- func NewRoute[T, B any](method, path string, handler any, e *Engine, options ...func(*BaseRoute)) Route[T, B]
- func Options[T, B any](s *Server, path string, controller func(ContextWithBody[B]) (T, error), ...) *Route[T, B]
- func OptionsStd(s *Server, path string, controller func(http.ResponseWriter, *http.Request), ...) *Route[any, any]
- func Patch[T, B any](s *Server, path string, controller func(ContextWithBody[B]) (T, error), ...) *Route[T, B]
- func PatchStd(s *Server, path string, controller func(http.ResponseWriter, *http.Request), ...) *Route[any, any]
- func Post[T, B any](s *Server, path string, controller func(ContextWithBody[B]) (T, error), ...) *Route[T, B]
- func PostStd(s *Server, path string, controller func(http.ResponseWriter, *http.Request), ...) *Route[any, any]
- func Put[T, B any](s *Server, path string, controller func(ContextWithBody[B]) (T, error), ...) *Route[T, B]
- func PutStd(s *Server, path string, controller func(http.ResponseWriter, *http.Request), ...) *Route[any, any]
- func Register[T, B any](s *Server, route Route[T, B], controller http.Handler, ...) *Route[T, B]deprecated
- func Registers[B, T any](engine *Engine, a Registerer[B, T]) *Route[B, T]
- type RouteWithParams
- type SchemaTag
- type Security
- func (security Security) CookieLogoutHandler(w http.ResponseWriter, r *http.Request)
- func (security Security) GenerateToken(claims jwt.Claims) (token string, err error)
- func (security Security) GenerateTokenToCookies(claims jwt.Claims, w http.ResponseWriter) (string, error)
- func (security Security) LoginHandler(verifyUserInfo func(user, password string) (jwt.Claims, error)) func(ContextWithBody[LoginPayload]) (tokenResponse, error)
- func (security Security) RefreshHandler(w http.ResponseWriter, r *http.Request)
- func (security Security) StdLoginHandler(verifyUserInfo func(r *http.Request) (jwt.Claims, error)) func(w http.ResponseWriter, r *http.Request)
- func (security Security) TokenToContext(searchFunc ...func(*http.Request) string) func(next http.Handler) http.Handler
- func (security Security) ValidateToken(token string) (*jwt.Token, error)
- type Sender
- type Server
- type StdRenderer
- type Templ
- type Timing
- type UnauthorizedError
- type ValidableCtx
Constants ¶
const JWTCookieName = "jwt_token"
Variables ¶
var ( // // 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") )
var ReadOptions = readOptions{ DisallowUnknownFields: true, MaxBodySize: maxBodySize, }
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.
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.
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.
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.
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 ¶
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 ¶
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 ¶
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 DefaultOpenAPIHandler ¶ added in v0.13.0
func DisableErrorHandler ¶ added in v0.18.0
func DisableErrorHandler() func(*Engine)
DisableErrorHandler overrides ErrorHandler with a simple pass-through
func ErrorHandler ¶
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
FuncName returns the name of a function and the name with package path
func GetToken ¶
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
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
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 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 OptionAddDescription ¶ added in v0.16.0
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
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
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
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
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
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
OptionMiddleware adds one or more route-scoped middleware.
func OptionOperationID ¶ added in v0.15.0
OptionOperationID adds an operation ID to the route.
func OptionOverrideDescription ¶ added in v0.17.0
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
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
OptionSummary adds a summary to the route.
func OptionTags ¶ added in v0.15.0
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 ¶
ReadJSON reads the request body as JSON. Can be used independently of Fuego framework. Customizable by modifying ReadOptions.
func ReadString ¶
ReadString reads the request body as string. Can be used independently of Fuego framework. Customizable by modifying ReadOptions.
func ReadURLEncoded ¶
ReadURLEncoded reads the request body as HTML Form.
func ReadXML ¶ added in v0.13.2
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
ReadYAML reads the request body as YAML. Can be used independently of Fuego framework. Customizable by modifying ReadOptions.
func Send ¶
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
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 ¶
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 TokenFromHeader ¶
func TokenFromQueryParam ¶
func TransformAndValidate ¶ added in v0.18.0
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
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 WithBasePath ¶
func WithCorsMiddleware
deprecated
added in
v0.13.0
func WithDisallowUnknownFields ¶
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
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 ¶
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
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
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
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
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 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
WithRequestContentType sets the accepted content types for the engine. By default, the accepted content types is */*.
func WithRouteOptions ¶ added in v0.15.1
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 ¶
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 ¶
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 ¶
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 ¶
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 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 WithoutStartupMessages ¶ added in v0.14.0
func WithoutStartupMessages() func(*Server)
WithoutStartupMessages disables the startup message
Types ¶
type AutoAuthConfig ¶
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 (*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 ContextWithPathParam ¶ added in v0.18.0
type CtxRenderer ¶ added in v0.9.0
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
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]) 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
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
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
ErrorWithDetail is an interface that can be implemented by an error to provide an additional detail message about the error
type ErrorWithStatus ¶
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 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) PublicError ¶ added in v0.18.6
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 ¶
type InTransformer ¶
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 MiddlewareConfig ¶ added in v0.18.1
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) 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 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 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 (e PathParamInvalidTypeError) Error() string
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
Registerer is an interface that allows registering routes. It can be implementable by any router.
type Renderer ¶ added in v0.9.0
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 ¶
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 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 OptionsStd ¶ added in v0.18.5
func Register
deprecated
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
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
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 (*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
SchemaTag is a struct that holds the name of the struct and the associated openapi3.SchemaRef
func SchemaTagFromType ¶ added in v0.15.0
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 ¶
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 ¶
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 ¶
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 ¶
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
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 ¶
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
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
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
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.
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
Timing is a struct to represent a server timing. Used in the Server-Timing header.
func (Timing) String ¶ added in v0.10.0
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
Source Files
¶
- ctx.go
- default_middlewares.go
- deserialization.go
- doc.go
- engine.go
- errors.go
- generic_mux.go
- html.go
- mock_context.go
- multi_return.go
- net_http_mux.go
- openapi.go
- openapi_description.go
- openapi_handler.go
- openapi_operations.go
- option.go
- param.go
- params.go
- perf.go
- route.go
- security.go
- serialization.go
- serve.go
- server.go
- validate_params.go
- validation.go
Directories
¶
Path | Synopsis |
---|---|
cmd
|
|
fuego
Module
|
|
examples
|
|
acme-tls
Module
|
|
basic
Module
|
|
crud-gorm
Module
|
|
custom-errors
Module
|
|
custom-serializer
Module
|
|
full-app-gourmet
Module
|
|
generate-opengraph-image
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. |