Documentation
¶
Overview ¶
Package router provides HTTP routing utilities with integrated OpenAPI/Swagger documentation. It combines Echo's routing capabilities with gswagger for API documentation generation.
Key Features ¶
- Route definition with built-in OpenAPI documentation - Authentication and authorization integration - Standardized request/response handling - TUS protocol support for file uploads - Pagination, sorting and filtering utilities - Automatic error response documentation
Getting Started ¶
Basic router setup:
router, err := router.NewRouter(router.APIInfo().
Title("My API").
Version("1.0.0").
Description("API for managing resources"))
if err != nil {
log.Fatal(err)
}
Route Definition ¶
The package provides a fluent interface for defining routes:
routes := router.DefineRoutes(
router.NewRoute("GET", "/users", getUsersHandler,
router.WithAccess(router.ACCESS_ADMIN_ROLE),
router.WithSwagger(
router.WithSummary("List Users"),
router.WithDescription("Returns paginated list of users"),
router.WithTags("Users"),
router.WithArrayResponse(http.StatusOK, "User list", User{}),
),
),
)
err := router.RegisterRoutes(router, accessSvc, "api", routes)
Swagger Documentation ¶
The package provides several helpers for common API patterns:
## Basic Endpoint
swagger := router.BasicSwagger(
"Public Info",
"Returns public information",
map[int]any{
http.StatusServiceUnavailable: map[string]string{"error": "Service unavailable"},
},
)
## Authenticated Endpoint
swagger := router.AuthSwagger(
"Get Profile",
"Returns user profile",
jwt.PurposeLogin,
map[int]any{
http.StatusNotFound: map[string]string{"error": "User not found"},
},
)
## List Endpoint with Pagination
swagger := router.ListEndpointSwagger(
"List Users",
"Paginated user list",
jwt.PurposeNone,
User{},
PaginationMeta{},
[]string{"name", "created_at"},
[]router.FilterParam{
{Name: "name_contains", Description: "Filter by name contains", SchemaValue: ""},
},
nil,
)
## TUS Upload Endpoints
routes := router.DefineRoutes(
router.NewRoute("POST", "/files", tusHandler,
router.WithSwagger(router.TusPostSwagger(
"Create Upload",
"Create new TUS upload session",
nil,
)),
),
// Other TUS methods...
)
Core Types ¶
- Router: Main router instance (*swagger.Router wrapper) - RouteDefinition: Defines a route and its documentation - APIInfoDefinition: API metadata builder - FieldSchema: Interface for sort/filter field definitions
Utilities ¶
- Parameter helpers:
- WithPathParam()
- WithQueryParam()
- WithHeaderParam()
- WithCookieParam()
- Pagination helpers:
- WithPaginationParams()
- WithSortParams()
- WithFilterParam()
- Error handling:
- DefaultPublicErrorResponses()
- DefaultAuthErrorResponses()
- WithCustomErrorResponses()
See package examples for more detailed usage.
Index ¶
- Constants
- Variables
- func AsErrorResponse(err error) interface{}
- func AuthSwagger(summary, description string, purpose jwt.Purpose, errResp map[int]any) swagger.Definitions
- func BasicSwagger(summary, description string, errResp map[int]any, opts ...SwaggerOption) swagger.Definitions
- func DefaultAuthErrorResponses() map[int]swagger.ContentValue
- func DefaultCoreErrorResponses() map[int]swagger.ContentValue
- func DefaultPublicErrorResponses() map[int]swagger.ContentValue
- func DefaultPublicFilesEnvSetup(r Router, envVar string) error
- func DefaultPublicFilesSetup(r Router, dirPath string) error
- func DefaultStaticEnvSetup(r Router, envVar string) error
- func DefaultStaticSetup(r Router, fsys any) error
- func DefineResponse(status int, description string, opts ...ResponseOption) map[int]swagger.ContentValue
- func DefineSwaggerErrorResponse(status int, errValue interface{}) map[int]swagger.ContentValue
- func DefineSwaggerErrorResponses(responses ...map[int]swagger.ContentValue) map[int]swagger.ContentValue
- func EmptyResponseSwagger() swagger.ContentValue
- func ErrorResponseSwagger(status int, body any) map[int]any
- func FileUploadSwaggerBody(fileFieldName string, fileDescription string, additionalFields map[string]any) *swagger.ContentValue
- func GetGroup(r Router) *echo.Group
- func GetGroupRouter(r Router) *echo.Group
- func GetRouter(r Router) *echo.Echo
- func GlobalSearchParam() swagger.ParameterValue
- func IsSubdomain(domain string) bool
- func ListEndpointSwagger(summary, description string, purpose jwt.Purpose, itemSchema any, ...) swagger.Definitions
- func MPASetup(r Router, fsys any) error
- func MPASetupWithAssets(r Router, fsys any, assetsDir string) error
- func MergeResponses(responses ...map[int]swagger.ContentValue) map[int]swagger.ContentValue
- func Middlewares(mw ...echo.MiddlewareFunc) []echo.MiddlewareFunc
- func MustDefaultPublicFilesEnvSetup(r Router, envVar string)
- func MustDefaultPublicFilesSetup(r Router, dirPath string)
- func MustDefaultStaticEnvSetup(r Router, envVar string)
- func MustDefaultStaticSetup(r Router, fsys any)
- func MustMPASetup(r Router, fsys any)
- func MustMPASetupWithAssets(r Router, fsys any, assetsDir string)
- func MustSetupStaticRoutes(r Router, cfg StaticConfig)
- func PaginatedResponseSwagger(summary, description string, purpose jwt.Purpose, ...) swagger.Definitions
- func RegisterRoutes(gRouter Router, accessSvc AccessService, subdomain string, ...) error
- func SetupStaticRoutes(r Router, cfg StaticConfig) error
- func SortParams(sortableFields []string) swagger.ParameterValue
- func SwaggerCookieParam(d swagger.Definitions, name, description string, schemaValue any) swagger.Definitions
- func SwaggerFilterParam(d swagger.Definitions, name, description string, schemaValue any) swagger.Definitions
- func SwaggerGlobalSearchParam(d swagger.Definitions) swagger.Definitions
- func SwaggerHeaderParam(d swagger.Definitions, name, description string, schemaValue any) swagger.Definitions
- func SwaggerPaginationParams(d swagger.Definitions) swagger.Definitions
- func SwaggerPathParam(d swagger.Definitions, name, description string, schemaValue any) swagger.Definitions
- func SwaggerQueryParam(d swagger.Definitions, name, description string, schemaValue any) swagger.Definitions
- func SwaggerSortParams(d swagger.Definitions, sortableFields []string) swagger.Definitions
- func TusDeleteSwagger(summary, description string, errResp map[int]any) swagger.Definitions
- func TusHeadSwagger(summary, description string, errResp map[int]any) swagger.Definitions
- func TusOptionsSwagger(summary, description string, errResp map[int]any) swagger.Definitions
- func TusPatchSwagger(summary, description string, errResp map[int]any) swagger.Definitions
- func TusPostSwagger(summary, description string, errResp map[int]any) swagger.Definitions
- func UpdateRouterInfo(r Router, info APIInfoDefinition)
- type APIInfoDefinition
- type AccessService
- type AppFilesystem
- type Content
- type ErrorResponder
- type ErrorResponse
- type ErrorWrapper
- type FieldSchema
- type FilterParam
- type Header
- type MockAccessService
- func (_mock *MockAccessService) CheckAccess(ctx context.Context, userId uint, fqdn string, path string, method string) (bool, error)
- func (_m *MockAccessService) EXPECT() *MockAccessService_Expecter
- func (_mock *MockAccessService) RegisterRoute(ctx context.Context, subdomain string, path string, method string, role string) error
- type MockAccessService_CheckAccess_Call
- type MockAccessService_Expecter
- func (_e *MockAccessService_Expecter) CheckAccess(ctx interface{}, userId interface{}, fqdn interface{}, path interface{}, ...) *MockAccessService_CheckAccess_Call
- func (_e *MockAccessService_Expecter) RegisterRoute(ctx interface{}, subdomain interface{}, path interface{}, method interface{}, ...) *MockAccessService_RegisterRoute_Call
- type MockAccessService_RegisterRoute_Call
- func (_c *MockAccessService_RegisterRoute_Call) Return(err error) *MockAccessService_RegisterRoute_Call
- func (_c *MockAccessService_RegisterRoute_Call) Run(...) *MockAccessService_RegisterRoute_Call
- func (_c *MockAccessService_RegisterRoute_Call) RunAndReturn(...) *MockAccessService_RegisterRoute_Call
- type Response
- type ResponseError
- type ResponseOption
- type Route
- type RouteDefinition
- type RouteOption
- func DefineOptions(opts ...RouteOption) []RouteOption
- func WithAccess(accessRole string) RouteOption
- func WithCors(configs ...cors.Config) RouteOption
- func WithMiddlewares(middleware ...echo.MiddlewareFunc) RouteOption
- func WithSwagger(opts ...SwaggerOption) RouteOption
- func WithSwaggerOptions(opts ...SwaggerOption) RouteOption
- type Router
- type RouterConfig
- type RouterOption
- func WithReflectorOptions(opts *jsonschema.Reflector) RouterOption
- func WithRouterBasePath(path string) RouterOption
- func WithRouterJSONDocsPath(path string) RouterOption
- func WithRouterOpenAPI(openapi *openapi3.T) RouterOption
- func WithRouterYAMLDocsPath(path string) RouterOption
- func WithServer(url string, description string) RouterOption
- func WithServers(servers []*openapi3.Server) RouterOption
- type SchemaProvider
- type StaticConfig
- type SwaggerOption
- func WithArrayResponse(status int, description string, itemValue interface{}) SwaggerOption
- func WithCookieParam(name, description string, schemaValue any) SwaggerOption
- func WithDescription(description string) SwaggerOption
- func WithErrorResponses(customErrors map[int]swagger.ContentValue) SwaggerOption
- func WithFileUpload(description string, required bool) SwaggerOption
- func WithFilterParam(name, description string, schemaValue any) SwaggerOption
- func WithFilterParamsFromSchema(schema FieldSchema) SwaggerOption
- func WithGlobalSearchParam() SwaggerOption
- func WithHeaderParam(name, description string, schemaValue any) SwaggerOption
- func WithListEndpoint(summary, description string, purpose jwt.Purpose, itemSchema any, ...) SwaggerOption
- func WithPaginatedResponse(itemType interface{}, paginationMeta interface{}) SwaggerOption
- func WithPaginationParams() SwaggerOption
- func WithPathParam(name, description string, schemaValue any) SwaggerOption
- func WithQueryParam(name, description string, schemaValue any) SwaggerOption
- func WithRequestBody(value interface{}, description string, required bool) SwaggerOption
- func WithResponseHeaders(status int, description string, content map[string]swagger.Schema, ...) SwaggerOption
- func WithSchema(schema FieldSchema) SwaggerOption
- func WithSortParams(sortableFields []string) SwaggerOption
- func WithSuccessResponse(status int, description string, opts ...ResponseOption) SwaggerOption
- func WithSummary(summary string) SwaggerOption
- func WithTags(tags ...string) SwaggerOption
Constants ¶
const ( ACCESS_USER_ROLE = "user" // Standard user access role ACCESS_ADMIN_ROLE = "admin" // Administrator access role )
Common access role constants
const ( SwaggerJSONPath = "/swagger.json" // Default path for JSON OpenAPI spec SwaggerYAMLPath = "/swagger.yaml" // Default path for YAML OpenAPI spec )
const ( // StaticAssetsPath is the URL path prefix for static assets StaticAssetsPath = "/static" // DefaultIndexFile is the default filename to serve for SPA fallback DefaultIndexFile = "index.html" )
const (
MediaTypeJSON = "application/json"
)
Variables ¶
var ( // StaticAssetsDir is the directory name where static assets are stored (derived from StaticAssetsPath) StaticAssetsDir = strings.TrimPrefix(StaticAssetsPath, "/") // FaviconFiles lists the supported favicon file extensions FaviconFiles = "ico,png,svg,gif" )
Functions ¶
func AsErrorResponse ¶ added in v0.5.0
func AsErrorResponse(err error) interface{}
AsErrorResponse converts an error to a response object
func AuthSwagger ¶
func AuthSwagger( summary, description string, purpose jwt.Purpose, errResp map[int]any, ) swagger.Definitions
AuthSwagger generates Swagger definitions for an authenticated endpoint. It includes standard security schemes (Bearer token) and common responses for authentication/authorization failures (401, 403).
Parameters: - summary: A brief summary of the operation. - description: A detailed description of the operation. - purpose: The JWT purpose required for this endpoint (e.g., jwt.PurposeLogin). - reqBody: An instance of the request body DTO for schema generation. Can be nil. - respBody: An instance of the success response body DTO for schema generation. Can be nil. - errResp: A map of additional error status codes and example response bodies.
func BasicSwagger ¶
func BasicSwagger( summary, description string, errResp map[int]any, opts ...SwaggerOption, ) swagger.Definitions
BasicSwagger generates basic Swagger definitions for an endpoint. It does not include authentication security schemes by default.
Parameters: - summary: A brief summary of the operation. - description: A detailed description of the operation. - reqBody: An instance of the request body DTO for schema generation. Can be nil. - respBody: An instance of the success response body DTO for schema generation. Can be nil. - errResp: A map of additional error status codes and response bodies (use DefineSwaggerErrorResponse(s) helpers).
func DefaultAuthErrorResponses ¶ added in v0.1.12
func DefaultAuthErrorResponses() map[int]swagger.ContentValue
DefaultAuthErrorResponses returns a map containing common HTTP error responses for authenticated routes. Includes core errors (400, 404, 500) plus auth-specific errors (401, 403).
func DefaultCoreErrorResponses ¶ added in v0.1.12
func DefaultCoreErrorResponses() map[int]swagger.ContentValue
DefaultCoreErrorResponses returns a map containing core HTTP error responses shared by all routes (400, 404, 500).
func DefaultPublicErrorResponses ¶ added in v0.1.12
func DefaultPublicErrorResponses() map[int]swagger.ContentValue
DefaultPublicErrorResponses returns a map containing common HTTP error responses for public routes. Includes core errors (400, 404, 500).
func DefaultPublicFilesEnvSetup ¶ added in v0.2.2
DefaultPublicFilesEnvSetup is a one-liner to setup public files from env var
func DefaultPublicFilesSetup ¶ added in v0.2.2
DefaultPublicFilesSetup is a one-liner to setup public file serving
func DefaultStaticEnvSetup ¶ added in v0.2.3
DefaultStaticEnvSetup is a one-liner to setup static file serving from an environment variable
func DefaultStaticSetup ¶ added in v0.2.3
DefaultStaticSetup is a one-liner to setup static file serving with the given filesystem
func DefineResponse ¶ added in v0.2.4
func DefineResponse(status int, description string, opts ...ResponseOption) map[int]swagger.ContentValue
DefineResponse creates a Response with the given status code and options
func DefineSwaggerErrorResponse ¶ added in v0.1.11
func DefineSwaggerErrorResponse(status int, errValue interface{}) map[int]swagger.ContentValue
DefineSwaggerErrorResponse creates a Swagger-compatible error response definition. Supports: - string messages - error interface - ResponseError implementations - ErrorResponse struct
func DefineSwaggerErrorResponses ¶ added in v0.1.11
func DefineSwaggerErrorResponses(responses ...map[int]swagger.ContentValue) map[int]swagger.ContentValue
DefineSwaggerErrorResponses combines multiple error responses for Swagger docs. Preserves existing success responses (2xx) when merging.
func EmptyResponseSwagger ¶
func EmptyResponseSwagger() swagger.ContentValue
EmptyResponseSwagger generates the Swagger definition for a 200 OK response with no body.
func ErrorResponseSwagger ¶
ErrorResponseSwagger generates a map for a single additional error response. Useful for adding one-off custom error responses to the errResp map.
func FileUploadSwaggerBody ¶
func FileUploadSwaggerBody( fileFieldName string, fileDescription string, additionalFields map[string]any, ) *swagger.ContentValue
FileUploadSwaggerBody generates the RequestBody definition for a file upload endpoint.
Parameters: - fileFieldName: The name of the form field for the file. - fileDescription: Description for the file field. - additionalFields: A map of additional form fields (name -> schema value).
func GetGroupRouter ¶ added in v0.1.3
func GlobalSearchParam ¶ added in v0.2.0
func GlobalSearchParam() swagger.ParameterValue
GlobalSearchParam returns the standard global search query parameter ('q').
func IsSubdomain ¶ added in v0.6.2
IsSubdomain checks if the given domain is a subdomain of its public suffix. Returns true if domain has parts before the public suffix, false otherwise.
func ListEndpointSwagger ¶
func ListEndpointSwagger( summary, description string, purpose jwt.Purpose, itemSchema any, paginationSchema any, sortableFields []string, filterParams []FilterParam, errResp map[int]any, opts ...SwaggerOption, ) swagger.Definitions
ListEndpointSwagger generates Swagger definitions for a list endpoint.
func MPASetup ¶ added in v0.6.6
MPASetup is a shorthand helper to configure Multi-Page Application support with the given filesystem. The fsys parameter can be either: - fs.FS (for embedded files) - http.FileSystem (for directory-based files)
func MPASetupWithAssets ¶ added in v0.6.6
MPASetupWithAssets is a shorthand helper to configure Multi-Page Application support with the given filesystem and custom assets directory. The fsys parameter can be either: - fs.FS (for embedded files) - http.FileSystem (for directory-based files)
func MergeResponses ¶ added in v0.4.4
func MergeResponses(responses ...map[int]swagger.ContentValue) map[int]swagger.ContentValue
MergeResponses combines multiple response maps while preserving success responses (2xx). Later responses override earlier ones for the same status code, except success responses which are preserved from their first occurrence.
func Middlewares ¶ added in v0.1.7
func Middlewares(mw ...echo.MiddlewareFunc) []echo.MiddlewareFunc
Middlewares is a convenience function that returns the provided middleware functions as a slice. This can be used to make middleware declarations more readable when passing multiple middlewares.
Example:
router.NewRoute("GET", "/path", handler,
WithMiddlewares(Middlewares(mw1, mw2, mw3)))
func MustDefaultPublicFilesEnvSetup ¶ added in v0.2.2
MustDefaultPublicFilesEnvSetup is a panic-on-error version of DefaultPublicFilesEnvSetup
func MustDefaultPublicFilesSetup ¶ added in v0.2.2
MustDefaultPublicFilesSetup is a panic-on-error version of DefaultPublicFilesSetup
func MustDefaultStaticEnvSetup ¶ added in v0.2.3
MustDefaultStaticEnvSetup is a panic-on-error version of DefaultStaticEnvSetup
func MustDefaultStaticSetup ¶ added in v0.2.3
MustDefaultStaticSetup is a panic-on-error version of DefaultStaticSetup
func MustMPASetup ¶ added in v0.6.6
MustMPASetup is a panic-on-error version of MPASetup
func MustMPASetupWithAssets ¶ added in v0.6.6
MustMPASetupWithAssets is a panic-on-error version of MPASetupWithAssets
func MustSetupStaticRoutes ¶ added in v0.2.2
func MustSetupStaticRoutes(r Router, cfg StaticConfig)
MustSetupStaticRoutes wraps SetupStaticRoutes and panics if configuration fails. Intended for use during application initialization where configuration errors should fail fast.
func PaginatedResponseSwagger ¶
func PaginatedResponseSwagger(summary, description string, purpose jwt.Purpose, itemSchema, paginationSchema any, errResp map[int]any) swagger.Definitions
PaginatedResponseSwagger generates Swagger definitions for an endpoint that returns a paginated list of items.
Parameters: - summary, description: Standard operation details. - purpose: JWT purpose (for authenticated endpoints). Use jwt.PurposeNone for public. - reqBody: Request body schema (can be nil). - itemSchema: An instance of the schema for a single item in the list. - paginationSchema: An instance of the schema for pagination metadata (can be nil). - errResp: Additional error responses.
func RegisterRoutes ¶
func RegisterRoutes( gRouter Router, accessSvc AccessService, subdomain string, routes []RouteDefinition, commonOpts ...RouteOption, ) error
RegisterRoutes registers a slice of RouteDefinitions with the provided Router. It handles: - Applying common middleware - Initializing route definitions - Registering routes with the router - Setting up access control
func SetupStaticRoutes ¶ added in v0.2.2
func SetupStaticRoutes(r Router, cfg StaticConfig) error
SetupStaticRoutes configures static file serving routes with optional SPA fallback.
Supports multiple configuration methods: - Directory-based serving via DirPath/EnvVar - Embedded filesystems via FS - Custom handler fallback via DefaultHandler
When using FS, IndexFile must be specified for SPA fallback behavior. Directory-based serving will automatically serve the index file for root requests.
Static assets are served under StaticAssetsPath ("/static") by default. All other requests fall back to the index file for SPA behavior.
Returns an error if: - FS is set but IndexFile is empty - No valid configuration is provided
func SortParams ¶ added in v0.2.0
func SortParams(sortableFields []string) swagger.ParameterValue
SortParams returns the standard sorting query parameters (_sort, _order). Parameters: - sortableFields: A list of fields that can be sorted. Used in the description.
func SwaggerCookieParam ¶ added in v0.2.0
func SwaggerCookieParam(d swagger.Definitions, name, description string, schemaValue any) swagger.Definitions
SwaggerCookieParam adds a cookie parameter definition to existing Swagger definitions. This is intended to be chained.
func SwaggerFilterParam ¶ added in v0.2.0
func SwaggerFilterParam(d swagger.Definitions, name, description string, schemaValue any) swagger.Definitions
SwaggerFilterParam adds a single filter query parameter to Swagger definitions. This helper is for simple filters like `fieldName_operator=value`.
Parameters: - d: The base Swagger definitions. - name: The full query parameter name (e.g., "age_gte", "status_eq"). - description: Description of the filter parameter. - schemaValue: An example value for schema generation (e.g., 30, "active").
func SwaggerGlobalSearchParam ¶ added in v0.2.0
func SwaggerGlobalSearchParam(d swagger.Definitions) swagger.Definitions
SwaggerGlobalSearchParam adds the standard global search query parameter ('q') to Swagger definitions.
func SwaggerHeaderParam ¶ added in v0.2.0
func SwaggerHeaderParam(d swagger.Definitions, name, description string, schemaValue any) swagger.Definitions
SwaggerHeaderParam adds a header parameter definition to existing Swagger definitions. This is intended to be chained.
func SwaggerPaginationParams ¶ added in v0.2.0
func SwaggerPaginationParams(d swagger.Definitions) swagger.Definitions
SwaggerPaginationParams adds standard pagination query parameters (_start, _end) to Swagger definitions. It takes the base Swagger definitions and returns the modified definitions for chaining.
func SwaggerPathParam ¶ added in v0.2.0
func SwaggerPathParam(d swagger.Definitions, name, description string, schemaValue any) swagger.Definitions
SwaggerPathParam adds a path parameter definition to existing Swagger definitions. This is intended to be chained.
func SwaggerQueryParam ¶ added in v0.2.0
func SwaggerQueryParam(d swagger.Definitions, name, description string, schemaValue any) swagger.Definitions
SwaggerQueryParam adds a query parameter definition to existing Swagger definitions. This is intended to be chained.
func SwaggerSortParams ¶ added in v0.2.0
func SwaggerSortParams(d swagger.Definitions, sortableFields []string) swagger.Definitions
SwaggerSortParams adds standard sorting query parameters (_sort, _order) to Swagger definitions. Parameters: - d: The base Swagger definitions - sortableFields: A list of fields that can be sorted. Used in the description.
func TusDeleteSwagger ¶
func TusDeleteSwagger(summary, description string, errResp map[int]any) swagger.Definitions
TusDeleteSwagger generates Swagger definitions for the TUS DELETE /files/{id} operation.
func TusHeadSwagger ¶
func TusHeadSwagger(summary, description string, errResp map[int]any) swagger.Definitions
TusHeadSwagger generates Swagger definitions for the TUS HEAD /files/{id} operation.
func TusOptionsSwagger ¶
func TusOptionsSwagger(summary, description string, errResp map[int]any) swagger.Definitions
TusOptionsSwagger generates Swagger definitions for the TUS OPTIONS /files operation.
func TusPatchSwagger ¶
func TusPatchSwagger(summary, description string, errResp map[int]any) swagger.Definitions
TusPatchSwagger generates Swagger definitions for the TUS PATCH /files/{id} operation.
func TusPostSwagger ¶
func TusPostSwagger(summary, description string, errResp map[int]any) swagger.Definitions
TusPostSwagger generates Swagger definitions for the TUS POST /files operation.
func UpdateRouterInfo ¶ added in v0.3.4
func UpdateRouterInfo(r Router, info APIInfoDefinition)
UpdateRouterInfo updates the OpenAPI info for a router using the provided APIInfoDefinition
Types ¶
type APIInfoDefinition ¶
type APIInfoDefinition interface {
Title(title string) APIInfoDefinition
GetTitle() string
Version(version string) APIInfoDefinition
GetVersion() string
Description(desc string) APIInfoDefinition
GetDescription() string
Contact(email, name string) APIInfoDefinition
GetContact() (email, name string)
License(name, url string) APIInfoDefinition
GetLicense() (name, url string)
TermsOfService(terms string) APIInfoDefinition
GetTermsOfService() string
// contains filtered or unexported methods
}
APIInfoDefinition defines the contract for building OpenAPI info metadata APIInfoDefinition defines the contract for building OpenAPI info metadata. It provides a fluent interface for setting API documentation properties.
func APIInfo ¶
func APIInfo() APIInfoDefinition
APIInfo creates a new APIInfoDefinition builder with default values.
type AccessService ¶ added in v0.2.1
type AccessService interface {
// CheckAccess verifies if a user has access to a specific route
CheckAccess(ctx context.Context, userId uint, fqdn, path, method string) (bool, error)
// RegisterRoute registers a new route with its access requirements
RegisterRoute(ctx context.Context, subdomain, path, method, role string) error
}
AccessService defines the interface for route access control
type AppFilesystem ¶ added in v0.6.2
type AppFilesystem struct {
// contains filtered or unexported fields
}
AppFilesystem wraps an fs.FS to modify index.html content before serving it. It caches the modified content after first read for better performance.
func NewAppFilesystem ¶ added in v0.6.2
func NewAppFilesystem(fsys fs.FS, portalDomain string) *AppFilesystem
NewAppFilesystem creates a new AppFilesystem wrapping the provided fs.FS. It automatically determines if the portalDomain is a subdomain using IsSubdomain.
type Content ¶ added in v0.2.4
type Content struct {
MediaType string
Schema interface{}
}
Content defines the response content for a specific media type
type ErrorResponder ¶ added in v0.5.0
type ErrorResponder interface {
ResponseError
Headers() map[string]string
}
ErrorResponder extends ResponseError with header support
type ErrorResponse ¶ added in v0.5.0
type ErrorResponse struct {
Message string `json:"error"`
}
ErrorResponse is the default error response format for simple errors
func (ErrorResponse) Error ¶ added in v0.5.0
func (e ErrorResponse) Error() string
func (ErrorResponse) HttpStatus ¶ added in v0.5.0
func (e ErrorResponse) HttpStatus() int
type ErrorWrapper ¶ added in v0.5.0
ErrorWrapper is a helper to implement ResponseError for simple errors
func (*ErrorWrapper) Error ¶ added in v0.5.0
func (e *ErrorWrapper) Error() string
func (*ErrorWrapper) HttpStatus ¶ added in v0.5.0
func (e *ErrorWrapper) HttpStatus() int
type FieldSchema ¶
type FieldSchema interface {
SortableFields() []string
FilterOperators() map[string][]string // field -> []operator
}
FieldSchema defines the interface for providing field-level schema information used to generate sorting and filtering documentation.
type FilterParam ¶
type FilterParam struct {
Name string // The full query parameter name (e.g., "age_gte", "status_eq")
Description string
SchemaValue any // An example value for schema generation
}
FilterParam defines the details for a single filter query parameter.
type MockAccessService ¶ added in v0.6.2
MockAccessService is an autogenerated mock type for the AccessService type
func NewMockAccessService ¶ added in v0.6.2
func NewMockAccessService(t interface {
mock.TestingT
Cleanup(func())
}) *MockAccessService
NewMockAccessService creates a new instance of MockAccessService. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. The first argument is typically a *testing.T value.
func (*MockAccessService) CheckAccess ¶ added in v0.6.2
func (_mock *MockAccessService) CheckAccess(ctx context.Context, userId uint, fqdn string, path string, method string) (bool, error)
CheckAccess provides a mock function for the type MockAccessService
func (*MockAccessService) EXPECT ¶ added in v0.6.2
func (_m *MockAccessService) EXPECT() *MockAccessService_Expecter
func (*MockAccessService) RegisterRoute ¶ added in v0.6.2
func (_mock *MockAccessService) RegisterRoute(ctx context.Context, subdomain string, path string, method string, role string) error
RegisterRoute provides a mock function for the type MockAccessService
type MockAccessService_CheckAccess_Call ¶ added in v0.6.2
MockAccessService_CheckAccess_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CheckAccess'
func (*MockAccessService_CheckAccess_Call) Return ¶ added in v0.6.2
func (_c *MockAccessService_CheckAccess_Call) Return(b bool, err error) *MockAccessService_CheckAccess_Call
func (*MockAccessService_CheckAccess_Call) Run ¶ added in v0.6.2
func (_c *MockAccessService_CheckAccess_Call) Run(run func(ctx context.Context, userId uint, fqdn string, path string, method string)) *MockAccessService_CheckAccess_Call
func (*MockAccessService_CheckAccess_Call) RunAndReturn ¶ added in v0.6.2
func (_c *MockAccessService_CheckAccess_Call) RunAndReturn(run func(ctx context.Context, userId uint, fqdn string, path string, method string) (bool, error)) *MockAccessService_CheckAccess_Call
type MockAccessService_Expecter ¶ added in v0.6.2
type MockAccessService_Expecter struct {
// contains filtered or unexported fields
}
func (*MockAccessService_Expecter) CheckAccess ¶ added in v0.6.2
func (_e *MockAccessService_Expecter) CheckAccess(ctx interface{}, userId interface{}, fqdn interface{}, path interface{}, method interface{}) *MockAccessService_CheckAccess_Call
CheckAccess is a helper method to define mock.On call
- ctx context.Context
- userId uint
- fqdn string
- path string
- method string
func (*MockAccessService_Expecter) RegisterRoute ¶ added in v0.6.2
func (_e *MockAccessService_Expecter) RegisterRoute(ctx interface{}, subdomain interface{}, path interface{}, method interface{}, role interface{}) *MockAccessService_RegisterRoute_Call
RegisterRoute is a helper method to define mock.On call
- ctx context.Context
- subdomain string
- path string
- method string
- role string
type MockAccessService_RegisterRoute_Call ¶ added in v0.6.2
MockAccessService_RegisterRoute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RegisterRoute'
func (*MockAccessService_RegisterRoute_Call) Return ¶ added in v0.6.2
func (_c *MockAccessService_RegisterRoute_Call) Return(err error) *MockAccessService_RegisterRoute_Call
func (*MockAccessService_RegisterRoute_Call) Run ¶ added in v0.6.2
func (_c *MockAccessService_RegisterRoute_Call) Run(run func(ctx context.Context, subdomain string, path string, method string, role string)) *MockAccessService_RegisterRoute_Call
func (*MockAccessService_RegisterRoute_Call) RunAndReturn ¶ added in v0.6.2
func (_c *MockAccessService_RegisterRoute_Call) RunAndReturn(run func(ctx context.Context, subdomain string, path string, method string, role string) error) *MockAccessService_RegisterRoute_Call
type ResponseError ¶ added in v0.1.11
ResponseError defines the interface for rich error responses that can provide HTTP status codes and custom serialization.
type ResponseOption ¶ added in v0.2.4
type ResponseOption func(*Response)
ResponseOption defines a function type for modifying Response properties
func WithCacheControl ¶ added in v0.2.4
func WithCacheControl(value string) ResponseOption
WithCacheControl helper for cache headers
func WithContent ¶ added in v0.2.4
func WithContent(mediaType string, schema interface{}) ResponseOption
WithContent creates a ResponseOption that sets the response content
func WithHeader ¶ added in v0.2.4
func WithHeader(name, description string) ResponseOption
WithHeader creates a ResponseOption that adds a response header
func WithJSONContent ¶ added in v0.2.4
func WithJSONContent(schema interface{}) ResponseOption
WithJSONContent helper for common JSON responses
func WithTotalCountHeader ¶ added in v0.2.4
func WithTotalCountHeader() ResponseOption
WithTotalCountHeader adds the X-Total-Count header to a response
type Route ¶ added in v0.1.1
type Route = RouteDefinition
Route is an alias for RouteDefinition for backwards compatibility.
type RouteDefinition ¶
type RouteDefinition struct {
// Path is the URL path for the route (e.g., "/users/{id}").
Path string
// Method is the HTTP method for the route (e.g., "GET", "POST").
Method string
// Handler is the echo.HandlerFunc that handles the request.
Handler echo.HandlerFunc
// Access is the required access role for this route (e.g., core.ACCESS_ADMIN_ROLE).
Access string
// Swagger contains the OpenAPI definitions for this route.
Swagger swagger.Definitions
// Middlewares contains route-specific middleware chain
Middlewares []echo.MiddlewareFunc
// CorsConfig stores the CORS middleware configuration for the route
CorsConfig *cors.Config
}
RouteDefinition defines a single HTTP route and its associated documentation and middleware.
func DefineRoutes ¶
func DefineRoutes(routes ...RouteDefinition) []RouteDefinition
DefineRoutes is a helper function to create a slice of RouteDefinition from a variable number of arguments. This allows defining routes without explicitly typing the slice literal. Example: routes := httputil.DefineRoutes(
{...}, // RouteDefinition 1
{...}, // RouteDefinition 2
)
func NewRoute ¶
func NewRoute(method, path string, handler echo.HandlerFunc, opts ...RouteOption) RouteDefinition
NewRoute creates a new RouteDefinition with the given method, path and handler, applying any provided RouteOptions.
type RouteOption ¶
type RouteOption func(*RouteDefinition)
RouteOption defines a function type for modifying RouteDefinition properties.
func DefineOptions ¶ added in v0.1.8
func DefineOptions(opts ...RouteOption) []RouteOption
DefineOptions converts variadic RouteOption arguments into a slice of RouteOptions. This helper function allows cleaner syntax when defining routes with multiple options.
Example:
router.NewRoute("GET", "/path", handler,
DefineOptions(
WithAccess(ACCESS_ADMIN_ROLE),
WithMiddlewares(mw1, mw2),
)...,
)
func WithAccess ¶
func WithAccess(accessRole string) RouteOption
Option setters WithAccess creates a RouteOption that sets the required access role for a route.
func WithCors ¶ added in v0.6.0
func WithCors(configs ...cors.Config) RouteOption
WithCors creates a RouteOption that sets CORS configuration for the route. The CORS middleware will be prepended to the middleware chain. If no configs are provided, an empty config will be used which will apply defaults.
func WithMiddlewares ¶ added in v0.1.1
func WithMiddlewares(middleware ...echo.MiddlewareFunc) RouteOption
WithMiddlewares creates a RouteOption that adds middleware functions to a route. Middlewares will be executed in the order they are provided.
func WithSwagger ¶
func WithSwagger(opts ...SwaggerOption) RouteOption
WithSwagger creates a RouteOption that sets the Swagger documentation definitions for a route. Automatically includes appropriate error responses based on access level. Preserves any existing success responses (2xx status codes) and allows custom success responses from options to be merged.
func WithSwaggerOptions ¶ added in v0.1.12
func WithSwaggerOptions(opts ...SwaggerOption) RouteOption
WithSwaggerOptions creates a RouteOption that applies multiple Swagger definition options.
type Router ¶
type Router = *swagger.Router[echo.HandlerFunc, echo.MiddlewareFunc, es.Route]
func NewRouter ¶ added in v0.1.9
func NewRouter(info APIInfoDefinition, opts ...RouterOption) (Router, error)
NewRouter creates a new Echo router with Swagger integration and sensible defaults. This is a convenience wrapper that handles both Echo and Swagger router initialization.
Parameters:
- info: API metadata (use APIInfo() builder)
- opts: Optional router configuration options
Returns:
- Router: The Swagger-wrapped router
- error: Any initialization error
Example:
router, err := NewRouter(APIInfo().
Title("My API").
Version("1.0.0"))
if err != nil {
log.Fatal(err)
}
func NewSwaggerRouter ¶
func NewSwaggerRouter(info APIInfoDefinition, opts ...RouterOption) (Router, error)
NewSwaggerRouter creates a new gswagger Router instance from an echo.Echo with default OpenAPI options. It initializes the OpenAPI specification with the provided API info and sets up standard documentation paths.
Parameters:
- echoRouter: The base Echo router that will handle the actual HTTP requests
- info: API metadata including title, version, description etc (use APIInfo() builder)
Returns:
- *swagger.Router: Configured router ready for route registration
- error: Any initialization error
Example:
muxRouter := mux.NewRouter()
gRouter, err := NewSwaggerRouter(muxRouter, APIInfo().
Title("My API").
Version("1.0.0"))
if err != nil {
log.Fatal(err)
}
type RouterConfig ¶ added in v0.4.0
type RouterConfig struct {
EchoRouter *echo.Echo
OpenAPI *openapi3.T
Options swagger.Options[echo.HandlerFunc, echo.MiddlewareFunc, es.Route]
PathPrefix string
ReflectorOptions *jsonschema.Reflector
}
RouterConfig holds configuration for router initialization
type RouterOption ¶ added in v0.1.9
type RouterOption func(*RouterConfig)
RouterOption defines a function type for configuring router initialization.
func WithReflectorOptions ¶ added in v0.4.5
func WithReflectorOptions(opts *jsonschema.Reflector) RouterOption
WithReflectorOptions configures the jsonschema reflector options used for schema generation.
func WithRouterBasePath ¶ added in v0.4.0
func WithRouterBasePath(path string) RouterOption
WithRouterBasePath sets the base path prefix for all routes
func WithRouterJSONDocsPath ¶ added in v0.4.0
func WithRouterJSONDocsPath(path string) RouterOption
WithRouterJSONDocsPath sets the path for JSON documentation
func WithRouterOpenAPI ¶ added in v0.4.0
func WithRouterOpenAPI(openapi *openapi3.T) RouterOption
WithRouterOpenAPI allows custom OpenAPI configuration
func WithRouterYAMLDocsPath ¶ added in v0.4.0
func WithRouterYAMLDocsPath(path string) RouterOption
WithRouterYAMLDocsPath sets the path for YAML documentation
func WithServer ¶ added in v0.4.1
func WithServer(url string, description string) RouterOption
WithServer adds a server URL to the OpenAPI spec
func WithServers ¶ added in v0.4.1
func WithServers(servers []*openapi3.Server) RouterOption
WithServers replaces all server URLs in the OpenAPI spec
type SchemaProvider ¶
type SchemaProvider interface {
ForType(any) FieldSchema
}
SchemaProvider defines an interface for providing schema information based on type.
type StaticConfig ¶ added in v0.2.2
type StaticConfig struct {
// DirPath is the filesystem path to the directory containing static files.
// If empty, EnvVar will be checked instead.
DirPath string
// EnvVar specifies an environment variable containing the static files directory path.
// Only used if DirPath is empty.
EnvVar string
// AssetsDir specifies the directory name where static assets are stored.
// Defaults to StaticAssetsDir ("static") if empty.
AssetsDir string
// DefaultHandler is used as a fallback handler when no directory or FS is provided.
// Typically an http.FileServer or similar.
DefaultHandler http.Handler
// FS specifies an embedded filesystem (like embed.FS) to serve files from.
FS fs.FS
// IndexFile is the name of the fallback file to serve for SPA routes (e.g. "index.html").
// Only used when MPA is false.
IndexFile string
// MPA enables Multi-Page Application mode where files are served directly instead of SPA fallback.
// When true, IndexFile is ignored.
MPA bool
}
StaticConfig defines configuration options for serving static files. Only one of these fields should be set: - DirPath or EnvVar for directory-based serving - FS for embedded filesystems - DefaultHandler for custom handler fallback
func PublicFilesConfig ¶ added in v0.2.2
func PublicFilesConfig(dirPath string) StaticConfig
PublicFilesConfig returns a StaticConfig for serving public files from disk
func PublicFilesEnvConfig ¶ added in v0.2.2
func PublicFilesEnvConfig(envVar string) StaticConfig
PublicFilesEnvConfig returns a StaticConfig that reads the directory path from an environment variable
func StaticConfigFromEnv ¶ added in v0.2.3
func StaticConfigFromEnv(envVar string) StaticConfig
StaticConfigFromEnv returns a StaticConfig that reads the filesystem path from an environment variable. Uses os.DirFS to create the filesystem from the directory path. Returns empty StaticConfig if envVar is not set or empty.
func StaticConfigWithFS ¶ added in v0.2.3
func StaticConfigWithFS(fsys any) StaticConfig
StaticConfigWithFS returns a StaticConfig with the given filesystem and SPA fallback to DefaultIndexFile. The fsys parameter can be either: - fs.FS (for embedded files) - http.FileSystem (for directory-based files) - nil (will return empty StaticConfig)
type SwaggerOption ¶
type SwaggerOption func(*swagger.Definitions, string)
SwaggerOption defines a function type for modifying swagger.Definitions. Used to apply customizations to OpenAPI/Swagger documentation.
func WithArrayResponse ¶ added in v0.1.12
func WithArrayResponse(status int, description string, itemValue interface{}) SwaggerOption
WithArrayResponse creates a Swagger option for array response definition.
func WithCookieParam ¶
func WithCookieParam(name, description string, schemaValue any) SwaggerOption
WithCookieParam creates a SwaggerOption that adds a cookie parameter definition.
func WithDescription ¶ added in v0.1.12
func WithDescription(description string) SwaggerOption
WithDescription creates a Swagger option for setting description.
func WithErrorResponses ¶ added in v0.3.0
func WithErrorResponses(customErrors map[int]swagger.ContentValue) SwaggerOption
WithErrorResponses creates a SwaggerOption that merges custom error responses with default responses based on access level while preserving existing success responses. The merging follows these rules: 1. Existing success responses (2xx) are preserved 2. Default error responses are added if not already present 3. Custom error responses override defaults
func WithFileUpload ¶ added in v0.1.12
func WithFileUpload(description string, required bool) SwaggerOption
WithFileUpload creates a Swagger option for file upload definition.
func WithFilterParam ¶
func WithFilterParam(name, description string, schemaValue any) SwaggerOption
WithFilterParam creates a SwaggerOption that adds a filter parameter.
func WithFilterParamsFromSchema ¶ added in v0.2.4
func WithFilterParamsFromSchema(schema FieldSchema) SwaggerOption
WithFilterParamsFromSchema creates a SwaggerOption that adds all filter parameters from a FieldSchema's FilterOperators() map. Supports multiple formats: - Simple: field_operator=value (e.g. age_gt=30) - Array values: field_operator=value1,value2,value3 or field_operator[]=value1&field_operator[]=value2 - Complex: filters[field][operator]=value (e.g. filters[age][gt]=30)
func WithGlobalSearchParam ¶
func WithGlobalSearchParam() SwaggerOption
WithGlobalSearchParam creates a SwaggerOption that adds the global search parameter.
func WithHeaderParam ¶
func WithHeaderParam(name, description string, schemaValue any) SwaggerOption
WithHeaderParam creates a SwaggerOption that adds a header parameter definition.
func WithListEndpoint ¶ added in v0.2.4
func WithListEndpoint( summary, description string, purpose jwt.Purpose, itemSchema any, paginationSchema any, sortableFields []string, filterParams []FilterParam, opts ...SwaggerOption, ) SwaggerOption
WithListEndpoint creates a SwaggerOption for configuring a list endpoint with pagination, sorting and filtering. It includes authentication, pagination, sorting, global search, and specific filter parameters.
Parameters: - summary, description: Standard operation details. - purpose: JWT purpose (for authenticated endpoints). Use jwt.PurposeNone for public. - itemSchema: An instance of the schema for a single item in the list response. - paginationSchema: An instance of the schema for pagination metadata in the response (can be nil). - sortableFields: A list of fields that can be sorted. - filterParams: A slice of FilterParam structs defining additional filter query parameters. - opt: Additional SwaggerOption to apply to the definitions.
func WithPaginatedResponse ¶ added in v0.2.4
func WithPaginatedResponse(itemType interface{}, paginationMeta interface{}) SwaggerOption
WithPaginatedResponse creates a paginated list response helper
func WithPaginationParams ¶
func WithPaginationParams() SwaggerOption
WithPaginationParams creates a SwaggerOption that adds standard pagination parameters.
func WithPathParam ¶
func WithPathParam(name, description string, schemaValue any) SwaggerOption
WithPathParam creates a SwaggerOption that adds a path parameter definition.
func WithQueryParam ¶
func WithQueryParam(name, description string, schemaValue any) SwaggerOption
WithQueryParam creates a SwaggerOption that adds a query parameter definition.
func WithRequestBody ¶ added in v0.1.12
func WithRequestBody(value interface{}, description string, required bool) SwaggerOption
WithRequestBody creates a Swagger option for request body definition.
func WithResponseHeaders ¶ added in v0.1.12
func WithResponseHeaders(status int, description string, content map[string]swagger.Schema, headers map[string]string) SwaggerOption
WithResponseHeaders creates a Swagger option for response with headers.
func WithSchema ¶
func WithSchema(schema FieldSchema) SwaggerOption
WithSchema creates a SwaggerOption that adds sorting and filtering parameters based on the provided FieldSchema implementation.
func WithSortParams ¶
func WithSortParams(sortableFields []string) SwaggerOption
WithSortParams creates a SwaggerOption that adds standard sorting parameters.
func WithSuccessResponse ¶ added in v0.2.4
func WithSuccessResponse(status int, description string, opts ...ResponseOption) SwaggerOption
WithSuccessResponse creates a SwaggerOption that adds a success response while preserving existing responses. The success response will not overwrite any existing response for the same status code.
func WithSummary ¶ added in v0.1.12
func WithSummary(summary string) SwaggerOption
WithSummary creates a Swagger option for setting summary.
func WithTags ¶ added in v0.1.12
func WithTags(tags ...string) SwaggerOption
WithTags creates a Swagger option for adding tags.