Documentation
¶
Overview ¶
Package notelink provides a framework for generating API documentation and integrating it with a Fiber web server. It allows developers to define endpoints with parameters, schemas, and authentication, and automatically generates an interactive HTML documentation page.
The package supports:
- Endpoint documentation with methods, paths, descriptions, and responses
- Parameter definitions (query, path, header)
- Automatic TypeScript schema generation from Go structs
- JWT authentication middleware
- Interactive API testing via a generated HTML interface
To use this package, create an ApiNote instance with a configuration and JWT secret, then define routes using the DocumentedRoute method. The documentation is served at "/api-docs" by default.
Example:
config := notelink.Config{Title: "My API", Host: "localhost:8080"}
api := notelink.NewApiNote(&config, "secret-key")
api.DocumentedRoute("GET", "/api/v1/hello", "Say hello", map[string]string{"200": "Success"}, handler, nil)
api.Listen()
Index ¶
- func ValidateParameters(c fiber.Ctx, params []Parameter) error
- func ValidateRequestBody(c fiber.Ctx, schema interface{}) error
- type ApiNote
- func (an *ApiNote) DocumentedRoute(input *DocumentedRouteInput) error
- func (an *ApiNote) ExportOpenAPIToFile(filepath string) error
- func (an *ApiNote) Fiber() *fiber.App
- func (an *ApiNote) GenerateOpenAPISpec() *OpenAPISpec
- func (an *ApiNote) Handler() fiber.Handler
- func (an *ApiNote) JWTMiddleware() fiber.Handler
- func (an *ApiNote) Listen() error
- func (an *ApiNote) ScalarUIHandler() fiber.Handler
- func (an *ApiNote) SwaggerUIHandler() fiber.Handler
- func (an *ApiNote) Use(middleware ...fiber.Handler)
- func (an *ApiNote) UseCustomAuth(middleware ...fiber.Handler)
- func (an *ApiNote) UseJWT()
- type Components
- type Config
- type DocumentedRouteInput
- type Endpoint
- type JSONSchema
- type MediaType
- type OpenAPIInfo
- type OpenAPIServer
- type OpenAPISpec
- type Operation
- type Parameter
- type ParameterSpec
- type PathItem
- type RequestBody
- type Response
- type SecurityScheme
- type ValidationError
- type ValidationErrorResponse
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ValidateParameters ¶ added in v1.0.0
ValidateParameters validates path/query/header parameters
func ValidateRequestBody ¶ added in v1.0.0
ValidateRequestBody validates request body against schema
Types ¶
type ApiNote ¶
type ApiNote struct {
// contains filtered or unexported fields
}
ApiNote is the main structure for API documentation and routing. It integrates with a Fiber application to serve both the API endpoints and their documentation.
func NewApiNote ¶
NewApiNote creates a new ApiNote instance with the provided configuration and JWT secret. It initializes a Fiber application and sets up the "/api-docs" route for documentation.
The config parameter defines the API's title, host, and other metadata. The jwtSecret is used for JWT authentication middleware.
Returns a pointer to the initialized ApiNote.
func (*ApiNote) DocumentedRoute ¶
func (an *ApiNote) DocumentedRoute(input *DocumentedRouteInput) error
DocumentedRoute registers an API endpoint with its documentation and handler. It accepts a DocumentedRouteInput object containing the route details and processes it to add the route to the Fiber app and store endpoint details for documentation.
Parameters:
- input: DocumentedRouteInput object containing method, path, description, responses, handler, params, schemasRequest, and schemasResponse
Example usage:
api.DocumentedRoute(notelink.DocumentedRouteInput{
Method: "POST",
Path: "/v3/users",
Description: "Create a new user (Authenticated)",
Responses: map[string]string{
"201": "User created",
"400": "Invalid input",
"401": "Unauthorized",
},
Handler: handlerFunc,
Params: []notelink.Parameter{},
SchemasRequest: CreateUserRequest{},
SchemasResponse: UserResponse{},
})
func (*ApiNote) ExportOpenAPIToFile ¶ added in v1.0.0
ExportOpenAPIToFile exports the OpenAPI specification to a JSON file
func (*ApiNote) Fiber ¶ added in v0.1.7
Fiber returns the underlying *fiber.App instance used by the ApiNote.
This allows external packages or components to directly access and configure the Fiber application (e.g., for adding routes, middleware, etc.).
func (*ApiNote) GenerateOpenAPISpec ¶ added in v1.0.0
func (an *ApiNote) GenerateOpenAPISpec() *OpenAPISpec
GenerateOpenAPISpec creates an OpenAPI 3.1 specification from registered endpoints
func (*ApiNote) Handler ¶
Handler returns a Fiber handler that serves the API documentation as HTML. The documentation is generated dynamically based on registered endpoints.
The returned handler sets the Content-Type to "text/html" and responds with status 200.
func (*ApiNote) JWTMiddleware ¶
JWTMiddleware returns a Fiber middleware handler that validates JWT tokens. It checks the "Authorization" header for a "Bearer" token and verifies it using the configured jwtSecret.
If the token is valid, it sets the "user_id" in the context from the token's "sub" claim. If invalid or missing, it returns a 401 Unauthorized response.
Example usage:
api.Use(api.JWTMiddleware())
func (*ApiNote) Listen ¶
Listen starts the Fiber server on the port specified in Config.Host. The Host field should be in the format "host:port" (e.g., "localhost:8080"). If no port is specified, it defaults to ":8080".
Returns an error if the server fails to start.
func (*ApiNote) ScalarUIHandler ¶ added in v1.0.0
ScalarUIHandler returns a handler that serves the Scalar API documentation UI Scalar is a modern alternative to Swagger UI with a cleaner interface
func (*ApiNote) SwaggerUIHandler ¶ added in v1.0.0
SwaggerUIHandler returns a handler that serves the Swagger UI The Swagger UI is loaded from CDN and points to /api-docs/openapi.json
func (*ApiNote) Use ¶
Use adds one or more middleware handlers to be applied to all subsequent routes. Middleware is executed in the order it is added. These middlewares are treated as custom (non-authentication) middleware and will not set the AuthRequired flag in endpoint documentation.
Example:
api.Use(RequestLoggerMiddleware()) // Apply custom logging to all following routes
func (*ApiNote) UseCustomAuth ¶ added in v0.3.1
UseCustomAuth adds custom authentication middleware to all subsequent routes. Routes defined after calling this method will have AuthRequired set to true in their documentation, indicating they require authentication.
This method allows you to use your own authentication logic instead of the built-in JWT middleware while still properly documenting that routes require authentication.
Example:
api.UseCustomAuth(MyCustomAuthMiddleware()) // All routes defined after this will require custom authentication
func (*ApiNote) UseJWT ¶ added in v0.3.1
func (an *ApiNote) UseJWT()
UseJWT adds JWT authentication middleware to all subsequent routes. Routes defined after calling this method will have AuthRequired set to true in their documentation, indicating they require authentication.
This is a convenience method that calls JWTMiddleware() and tracks it separately from custom middleware, allowing proper documentation of authentication requirements.
Example:
api.UseJWT() // All routes defined after this will require JWT authentication
type Components ¶ added in v1.0.0
type Components struct {
Schemas map[string]*JSONSchema `json:"schemas,omitempty"`
SecuritySchemes map[string]SecurityScheme `json:"securitySchemes,omitempty"`
}
type Config ¶
type Config struct {
Title string
Description string
Version string
Host string
BasePath string
AuthToken string // Optional authorization token (e.g., Bearer token)
DocsUI string // UI to use for /api-docs endpoint: "scalar" (default) or "swagger"
EnableValidation bool // Enable server-side validation (default: true)
StrictTypeValidation bool // Strict type checking vs coercion (default: false)
}
Config holds the API documentation configuration
type DocumentedRouteInput ¶ added in v0.2.0
type DocumentedRouteInput struct {
SchemasRequest interface{} `json:"schemasRequest"`
SchemasResponse interface{} `json:"schemasResponse"`
Responses map[string]string `json:"responses"`
Handler fiber.Handler `json:"handler"`
AuthRequired *bool `json:"authRequired"`
Method string `json:"method"`
Path string `json:"path"`
Description string `json:"description"`
Params []Parameter `json:"params"`
}
DocumentedRouteInput represents the input for registering a documented route
type Endpoint ¶
type Endpoint struct {
Method string
Path string
Description string
Responses map[string]string
RequestSchema interface{}
ResponseSchema interface{}
Parameters []Parameter
AuthRequired bool // Indicates if authorization is required
}
Endpoint represents a single API endpoint with schema and parameters
type JSONSchema ¶ added in v1.0.0
type JSONSchema struct {
AdditionalProperties interface{} `json:"additionalProperties,omitempty"`
Properties map[string]*JSONSchema `json:"properties,omitempty"`
Items *JSONSchema `json:"items,omitempty"`
Minimum *float64 `json:"minimum,omitempty"`
Type string `json:"type,omitempty"`
Format string `json:"format,omitempty"`
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
Ref string `json:"$ref,omitempty"`
Required []string `json:"required,omitempty"`
Nullable bool `json:"nullable,omitempty"`
}
JSONSchema represents JSON Schema (compatible with OpenAPI 3.1)
type MediaType ¶ added in v1.0.0
type MediaType struct {
Schema *JSONSchema `json:"schema,omitempty"`
Example interface{} `json:"example,omitempty"`
}
type OpenAPIInfo ¶ added in v1.0.0
type OpenAPIServer ¶ added in v1.0.0
type OpenAPISpec ¶ added in v1.0.0
type OpenAPISpec struct {
OpenAPI string `json:"openapi"`
Info OpenAPIInfo `json:"info"`
Servers []OpenAPIServer `json:"servers,omitempty"`
Paths map[string]PathItem `json:"paths"`
Components *Components `json:"components,omitempty"`
Security []map[string][]string `json:"security,omitempty"`
}
OpenAPI 3.1 root structure
type Operation ¶ added in v1.0.0
type Operation struct {
OperationID string `json:"operationId"`
Summary string `json:"summary,omitempty"`
Description string `json:"description,omitempty"`
Parameters []ParameterSpec `json:"parameters,omitempty"`
RequestBody *RequestBody `json:"requestBody,omitempty"`
Responses map[string]Response `json:"responses"`
Security []map[string][]string `json:"security,omitempty"`
Tags []string `json:"tags,omitempty"`
}
type Parameter ¶
type Parameter struct {
Name string
In string // "query", "path", "header"
Type string // e.g., "string", "number", "boolean"
Description string
Required bool
}
Parameter represents an API parameter
type ParameterSpec ¶ added in v1.0.0
type ParameterSpec struct {
Schema *JSONSchema `json:"schema"`
Name string `json:"name"`
In string `json:"in"` // "query", "path", "header", "cookie"
Description string `json:"description,omitempty"`
Required bool `json:"required,omitempty"`
}
type PathItem ¶ added in v1.0.0
type PathItem struct {
Get *Operation `json:"get,omitempty"`
Post *Operation `json:"post,omitempty"`
Put *Operation `json:"put,omitempty"`
Delete *Operation `json:"delete,omitempty"`
Patch *Operation `json:"patch,omitempty"`
Head *Operation `json:"head,omitempty"`
Options *Operation `json:"options,omitempty"`
Trace *Operation `json:"trace,omitempty"`
}
type RequestBody ¶ added in v1.0.0
type SecurityScheme ¶ added in v1.0.0
type SecurityScheme struct {
Type string `json:"type"` // "http", "apiKey", "oauth2", "openIdConnect"
Scheme string `json:"scheme,omitempty"`
BearerFormat string `json:"bearerFormat,omitempty"`
Description string `json:"description,omitempty"`
Name string `json:"name,omitempty"`
In string `json:"in,omitempty"`
}
type ValidationError ¶ added in v1.0.0
type ValidationError struct {
Field string `json:"field"`
Message string `json:"message"`
Type string `json:"type,omitempty"`
}
ValidationError represents a single validation error
type ValidationErrorResponse ¶ added in v1.0.0
type ValidationErrorResponse struct {
ErrorMessage string `json:"error"`
Errors []ValidationError `json:"errors,omitempty"`
}
ValidationErrorResponse represents the validation error response
func (*ValidationErrorResponse) Error ¶ added in v1.0.0
func (v *ValidationErrorResponse) Error() string
Error implements the error interface
