Documentation
¶
Overview ¶
Package okapi is a modern, minimalist HTTP web framework for Go, inspired by FastAPI's elegance. Designed for simplicity, performance, and developer happiness, it helps you build fast, scalable, and well-documented APIs with minimal boilerplate.
The framework is named after the okapi (/oʊˈkɑːpiː/), a rare and graceful mammal native to the rainforests of the northeastern Democratic Republic of the Congo. Just like its namesake — which resembles a blend of giraffe and zebra — Okapi blends simplicity and strength in a unique, powerful package.
Key Features:
Intuitive & Expressive API: Clean, declarative syntax for effortless route and middleware definition.
Automatic Request Binding: Seamlessly parse JSON, XML, form data, query params, headers, and path variables into structs.
Built-in Auth & Security: Native support for JWT, OAuth2, Basic Auth, and custom middleware.
First-Class Documentation: OpenAPI 3.0 & Swagger UI integrated out of the box—auto-generate API docs with minimal effort.
Modern Tooling: Route grouping, middleware chaining, static file serving, templating engine support, CORS management, fine-grained timeout controls.
Developer Experience: Minimal boilerplate, clear error handling, structured logging, and easy testing.
Okapi is built for speed, simplicity, and real-world use—whether you're prototyping or running in production.
For more information and documentation, visit: https://github.com/jkaninda/okapi
Index ¶
- Variables
- func DefaultErrorHandler(c *Context, code int, message string, err error) error
- func GenerateJwtToken(secret []byte, claims jwt.MapClaims, ttl time.Duration) (string, error)
- func IsClientError(code int) bool
- func IsError(code int) bool
- func IsServerError(code int) bool
- func LoadTLSConfig(certFile, keyFile, caFile string, clientAuth bool) (*tls.Config, error)
- func RegisterRoutes(o *Okapi, routes []RouteDefinition)
- func ValidateAddr(addr string) bool
- type AndExpr
- type Base64Serializer
- type BasicAuth
- type BasicAuthMiddleware
- type BodyLimit
- type C
- type Contact
- type ContainsExpr
- type Context
- func (c *Context) Abort(err error) error
- func (c *Context) AbortBadGateway(msg string, err ...error) error
- func (c *Context) AbortBadRequest(msg string, err ...error) error
- func (c *Context) AbortConflict(msg string, err ...error) error
- func (c *Context) AbortExpectationFailed(msg string, err ...error) error
- func (c *Context) AbortFailedDependency(msg string, err ...error) error
- func (c *Context) AbortForbidden(msg string, err ...error) error
- func (c *Context) AbortGatewayTimeout(msg string, err ...error) error
- func (c *Context) AbortGone(msg string, err ...error) error
- func (c *Context) AbortHTTPVersionNotSupported(msg string, err ...error) error
- func (c *Context) AbortInsufficientStorage(msg string, err ...error) error
- func (c *Context) AbortInternalServerError(msg string, err ...error) error
- func (c *Context) AbortLengthRequired(msg string, err ...error) error
- func (c *Context) AbortLocked(msg string, err ...error) error
- func (c *Context) AbortLoopDetected(msg string, err ...error) error
- func (c *Context) AbortMethodNotAllowed(msg string, err ...error) error
- func (c *Context) AbortMisdirectedRequest(msg string, err ...error) error
- func (c *Context) AbortNetworkAuthenticationRequired(msg string, err ...error) error
- func (c *Context) AbortNotAcceptable(msg string, err ...error) error
- func (c *Context) AbortNotExtended(msg string, err ...error) error
- func (c *Context) AbortNotFound(msg string, err ...error) error
- func (c *Context) AbortNotImplemented(msg string, err ...error) error
- func (c *Context) AbortNotModified(msg string, err ...error) error
- func (c *Context) AbortPaymentRequired(msg string, err ...error) error
- func (c *Context) AbortPreconditionFailed(msg string, err ...error) error
- func (c *Context) AbortPreconditionRequired(msg string, err ...error) error
- func (c *Context) AbortProxyAuthRequired(msg string, err ...error) error
- func (c *Context) AbortRequestEntityTooLarge(msg string, err ...error) error
- func (c *Context) AbortRequestHeaderFieldsTooLarge(msg string, err ...error) error
- func (c *Context) AbortRequestTimeout(msg string, err ...error) error
- func (c *Context) AbortRequestURITooLong(msg string, err ...error) error
- func (c *Context) AbortRequestedRangeNotSatisfiable(msg string, err ...error) error
- func (c *Context) AbortServiceUnavailable(msg string, err ...error) error
- func (c *Context) AbortTeapot(msg string, err ...error) error
- func (c *Context) AbortTooEarly(msg string, err ...error) error
- func (c *Context) AbortTooManyRequests(msg string, err ...error) error
- func (c *Context) AbortUnauthorized(msg string, err ...error) error
- func (c *Context) AbortUnavailableForLegalReasons(msg string, err ...error) error
- func (c *Context) AbortUnsupportedMediaType(msg string, err ...error) error
- func (c *Context) AbortUpgradeRequired(msg string, err ...error) error
- func (c *Context) AbortValidationError(msg string, err ...error) error
- func (c *Context) AbortValidationErrors(errors []ValidationError, msg ...string) error
- func (c *Context) AbortValidationErrorsWithProblemDetail(errors []ValidationError, msg ...string) error
- func (c *Context) AbortVariantAlsoNegotiates(msg string, err ...error) error
- func (c *Context) AbortWithError(code int, err error) error
- func (c *Context) AbortWithJSON(code int, jsonObj interface{}) error
- func (c *Context) AbortWithProblemDetail(problem *ProblemDetail) error
- func (c *Context) AbortWithStatus(code int, message string) error
- func (c *Context) Accept() []string
- func (c *Context) AcceptLanguage() []string
- func (c *Context) B(v any) error
- func (c *Context) Bind(out any) error
- func (c *Context) BindForm(v any) error
- func (c *Context) BindJSON(v any) error
- func (c *Context) BindMultipart(out any) error
- func (c *Context) BindProtoBuf(v proto.Message) error
- func (c *Context) BindQuery(v any) error
- func (c *Context) BindXML(v any) error
- func (c *Context) BindYAML(v any) error
- func (c *Context) ContentType() string
- func (c *Context) Context() context.Context
- func (c *Context) Cookie(name string) (string, error)
- func (c *Context) Copy() *Context
- func (c *Context) Created(v any) error
- func (c *Context) Data(code int, contentType string, data []byte) error
- func (c *Context) Error(code int, message string) error
- func (c *Context) ErrorBadGateway(message any) error
- func (c *Context) ErrorBadRequest(message any) error
- func (c *Context) ErrorConflict(message any) error
- func (c *Context) ErrorExpectationFailed(message any) error
- func (c *Context) ErrorFailedDependency(message any) error
- func (c *Context) ErrorForbidden(message any) error
- func (c *Context) ErrorGatewayTimeout(message any) error
- func (c *Context) ErrorGone(message any) error
- func (c *Context) ErrorHTTPVersionNotSupported(message any) error
- func (c *Context) ErrorInsufficientStorage(message any) error
- func (c *Context) ErrorInternalServerError(message any) error
- func (c *Context) ErrorLengthRequired(message any) error
- func (c *Context) ErrorLocked(message any) error
- func (c *Context) ErrorLoopDetected(message any) error
- func (c *Context) ErrorMethodNotAllowed(message any) error
- func (c *Context) ErrorMisdirectedRequest(message any) error
- func (c *Context) ErrorNetworkAuthenticationRequired(message any) error
- func (c *Context) ErrorNotAcceptable(message any) error
- func (c *Context) ErrorNotExtended(message any) error
- func (c *Context) ErrorNotFound(message any) error
- func (c *Context) ErrorNotImplemented(message any) error
- func (c *Context) ErrorNotModified(message any) error
- func (c *Context) ErrorPaymentRequired(message any) error
- func (c *Context) ErrorPreconditionFailed(message any) error
- func (c *Context) ErrorPreconditionRequired(message any) error
- func (c *Context) ErrorProxyAuthRequired(message any) error
- func (c *Context) ErrorRequestEntityTooLarge(message any) error
- func (c *Context) ErrorRequestHeaderFieldsTooLarge(message any) error
- func (c *Context) ErrorRequestTimeout(message any) error
- func (c *Context) ErrorRequestURITooLong(message any) error
- func (c *Context) ErrorRequestedRangeNotSatisfiable(message any) error
- func (c *Context) ErrorServiceUnavailable(message any) error
- func (c *Context) ErrorTeapot(message any) error
- func (c *Context) ErrorTooEarly(message any) error
- func (c *Context) ErrorTooManyRequests(message any) error
- func (c *Context) ErrorUnauthorized(message any) error
- func (c *Context) ErrorUnavailableForLegalReasons(message any) error
- func (c *Context) ErrorUnprocessableEntity(message any) error
- func (c *Context) ErrorUnsupportedMediaType(message any) error
- func (c *Context) ErrorUpgradeRequired(message any) error
- func (c *Context) ErrorVariantAlsoNegotiates(message any) error
- func (c *Context) Form(key string) string
- func (c *Context) FormFile(key string) (*multipart.FileHeader, error)
- func (c *Context) FormValue(key string) string
- func (c *Context) Get(key string) (any, bool)
- func (c *Context) GetBool(key string) bool
- func (c *Context) GetInt(key string) int
- func (c *Context) GetInt64(key string) int64
- func (c *Context) GetString(key string) string
- func (c *Context) GetTime(key string) (time.Time, bool)
- func (c *Context) HTML(code int, file string, data any) error
- func (c *Context) HTMLView(code int, templateStr string, data any) error
- func (c *Context) Header(key string) string
- func (c *Context) Headers() map[string][]string
- func (c *Context) IsSSE() bool
- func (c *Context) IsWebSocketUpgrade() bool
- func (c *Context) JSON(code int, v any) error
- func (c *Context) Logger() *slog.Logger
- func (c *Context) MaxMultipartMemory() int64
- func (c *Context) NoContent() error
- func (c *Context) OK(v any) error
- func (c *Context) Param(key string) string
- func (c *Context) Params() map[string]string
- func (c *Context) Path() string
- func (c *Context) PathParam(key string) string
- func (c *Context) Query(key string) string
- func (c *Context) QueryArray(key string) []string
- func (c *Context) QueryMap() map[string]string
- func (c *Context) RealIP() string
- func (c *Context) Redirect(code int, location string)
- func (c *Context) Referer() string
- func (c *Context) Render(code int, name string, data interface{}) error
- func (c *Context) Request() *http.Request
- func (c *Context) Respond(output any) error
- func (c *Context) Response() ResponseWriter
- func (c *Context) ResponseWriter() http.ResponseWriter
- func (c *Context) Return(output any) error
- func (c *Context) SSESendBinary(data []byte) error
- func (c *Context) SSESendData(data any) error
- func (c *Context) SSESendEvent(id, eventType string, data any) error
- func (c *Context) SSESendJSON(data any) error
- func (c *Context) SSESendText(text string) error
- func (c *Context) SSEStream(ctx context.Context, messageChan <-chan Message) error
- func (c *Context) SSEStreamWithOptions(ctx context.Context, messageChan <-chan Message, opts *StreamOptions) error
- func (c *Context) SSEvent(eventType string, data any) error
- func (c *Context) SendSSECustom(data any, serializer Serializer) error
- func (c *Context) SendSSEvent(id, eventType string, data any) error
- func (c *Context) ServeFile(path string)
- func (c *Context) ServeFileAttachment(path, filename string)
- func (c *Context) ServeFileFromFS(filepath string, fs http.FileSystem)
- func (c *Context) ServeFileInline(path, filename string)
- func (c *Context) Set(key string, value any)
- func (c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool)
- func (c *Context) SetErrorHandler(handler ErrorHandler)
- func (c *Context) SetHeader(key, value string)
- func (c *Context) SetMaxMultipartMemory(max int64)
- func (c *Context) ShouldBind(v any) (bool, error)
- func (c *Context) String(code int, data any) error
- func (c *Context) Text(code int, v any) error
- func (c *Context) WriteStatus(code int)
- func (c *Context) XML(code int, v any) error
- func (c *Context) YAML(code int, data any) error
- type Cors
- type Ctx
- type DocBuilder
- func (b *DocBuilder) AsOption() RouteOption
- func (b *DocBuilder) BearerAuth() *DocBuilder
- func (b *DocBuilder) Build() RouteOption
- func (b *DocBuilder) Deprecated() *DocBuilder
- func (b *DocBuilder) Description(description string) *DocBuilder
- func (b *DocBuilder) ErrorResponse(status int, v any) *DocBuilder
- func (b *DocBuilder) Header(name, typ, desc string, required bool) *DocBuilder
- func (b *DocBuilder) HeaderWithDefault(name, typ, desc string, required bool, defvalue any) *DocBuilder
- func (b *DocBuilder) Hide() *DocBuilder
- func (b *DocBuilder) OperationId(operationId string) *DocBuilder
- func (b *DocBuilder) PathParam(name, typ, desc string) *DocBuilder
- func (b *DocBuilder) PathParamWithDefault(name, typ, desc string, defvalue any) *DocBuilder
- func (b *DocBuilder) QueryParam(name, typ, desc string, required bool) *DocBuilder
- func (b *DocBuilder) QueryParamWithDefault(name, typ, desc string, required bool, defvalue any) *DocBuilder
- func (b *DocBuilder) RequestBody(v any) *DocBuilder
- func (b *DocBuilder) Response(statusOrValue any, vOptional ...any) *DocBuilder
- func (b *DocBuilder) ResponseHeader(name, typ string, desc ...string) *DocBuilder
- func (b *DocBuilder) Summary(summary string) *DocBuilder
- func (b *DocBuilder) Tags(tags ...string) *DocBuilder
- type EqualsExpr
- type ErrorFormat
- type ErrorHandler
- type ErrorHandlerConfig
- type ErrorResponse
- type Expression
- type ExpressionParser
- type ExternalDocs
- type Group
- func (g *Group) Delete(path string, h HandlerFunc, opts ...RouteOption) *Route
- func (g *Group) Deprecated() *Group
- func (g *Group) Disable() *Group
- func (g *Group) Enable() *Group
- func (g *Group) Get(path string, h HandlerFunc, opts ...RouteOption) *Route
- func (g *Group) Group(path string, middlewares ...Middleware) *Group
- func (g *Group) HandleHTTP(method, path string, h http.Handler, opts ...RouteOption)
- func (g *Group) HandleStd(method, path string, h func(http.ResponseWriter, *http.Request), ...)
- func (g *Group) Head(path string, h HandlerFunc, opts ...RouteOption) *Route
- func (g *Group) Okapi() *Okapi
- func (g *Group) Options(path string, h HandlerFunc, opts ...RouteOption) *Route
- func (g *Group) Patch(path string, h HandlerFunc, opts ...RouteOption) *Route
- func (g *Group) Post(path string, h HandlerFunc, opts ...RouteOption) *Route
- func (g *Group) Put(path string, h HandlerFunc, opts ...RouteOption) *Route
- func (g *Group) Register(routes ...RouteDefinition)
- func (g *Group) Use(m ...Middleware)
- func (g *Group) UseMiddleware(mw func(http.Handler) http.Handler)
- func (g *Group) WithBasicAuth() *Group
- func (g *Group) WithBearerAuth() *Group
- func (g *Group) WithSecurity(security []map[string][]string) *Group
- func (g *Group) WithTags(tags []string) *Group
- type HandlerFunc
- func H[I any](h func(*Context, *I) error) HandlerFunc
- func Handle[I any](h func(*Context, *I) error) HandlerFunc
- func HandleIO[I any, O any](h func(*Context, *I) (*O, error)) HandlerFunc
- func HandleO[O any](h func(*Context) (*O, error)) HandlerFunc
- func LoggerMiddleware(next HandlerFunc) HandlerFunc
- type JSONSerializer
- type JWTAuth
- type Jwk
- type Jwks
- type License
- type Location
- type Logger
- type M
- type Message
- type Middleware
- type NotExpr
- type OAuthFlow
- type OAuthFlows
- type Okapi
- func (o *Okapi) Any(path string, h HandlerFunc, opts ...RouteOption) *Route
- func (o *Okapi) Delete(path string, h HandlerFunc, opts ...RouteOption) *Route
- func (o *Okapi) DisableAccessLog() *Okapi
- func (o *Okapi) Get(path string, h HandlerFunc, opts ...RouteOption) *Route
- func (o *Okapi) GetContext() *Context
- func (o *Okapi) Group(prefix string, middlewares ...Middleware) *Group
- func (o *Okapi) Handle(method, path string, h HandlerFunc, opts ...RouteOption)
- func (o *Okapi) HandleHTTP(method, path string, h http.Handler, opts ...RouteOption)
- func (o *Okapi) HandleStd(method, path string, h func(http.ResponseWriter, *http.Request), ...)
- func (o *Okapi) Head(path string, h HandlerFunc, opts ...RouteOption) *Route
- func (o *Okapi) NoMethod(h HandlerFunc)
- func (o *Okapi) NoRoute(h HandlerFunc)
- func (o *Okapi) Options(path string, h HandlerFunc, opts ...RouteOption) *Route
- func (o *Okapi) Patch(path string, h HandlerFunc, opts ...RouteOption) *Route
- func (o *Okapi) Post(path string, h HandlerFunc, opts ...RouteOption) *Route
- func (o *Okapi) Put(path string, h HandlerFunc, opts ...RouteOption) *Route
- func (o *Okapi) Register(routes ...RouteDefinition)
- func (o *Okapi) RegisterSchemas(schemas map[string]*SchemaInfo) error
- func (o *Okapi) Routes() []Route
- func (o *Okapi) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (o *Okapi) SetContext(ctx *Context)
- func (o *Okapi) Shutdown(server *http.Server, ctx ...context.Context) error
- func (o *Okapi) Start() error
- func (o *Okapi) StartForTest(t TestingT) string
- func (o *Okapi) StartOn(port int) error
- func (o *Okapi) StartServer(server *http.Server) error
- func (o *Okapi) Static(prefix string, dir string)
- func (o *Okapi) StaticFS(prefix string, fs http.FileSystem)
- func (o *Okapi) StaticFile(path string, filepath string)
- func (o *Okapi) Stop() error
- func (o *Okapi) StopWithContext(ctx context.Context) error
- func (o *Okapi) Use(middlewares ...Middleware)
- func (o *Okapi) UseMiddleware(mw func(http.Handler) http.Handler)
- func (o *Okapi) WaitForServer(timeout time.Duration) string
- func (o *Okapi) With(options ...OptionFunc) *Okapi
- func (o *Okapi) WithAddr(addr string) *Okapi
- func (o *Okapi) WithCORS(cors Cors) *Okapi
- func (o *Okapi) WithContext(ctx context.Context) *Okapi
- func (o *Okapi) WithDebug() *Okapi
- func (o *Okapi) WithDefaultErrorHandler() *Okapi
- func (o *Okapi) WithDefaultRenderer(templatePath string) *Okapi
- func (o *Okapi) WithErrorHandler(handler ErrorHandler) *Okapi
- func (o *Okapi) WithIdleTimeout(seconds int) *Okapi
- func (o *Okapi) WithLogger(logger *slog.Logger) *Okapi
- func (o *Okapi) WithMaxMultipartMemory(max int64) *Okapi
- func (o *Okapi) WithOpenAPIDisabled() *Okapi
- func (o *Okapi) WithOpenAPIDocs(cfg ...OpenAPI) *Okapi
- func (o *Okapi) WithPort(port int) *Okapi
- func (o *Okapi) WithProblemDetailErrorHandler(config *ErrorHandlerConfig) *Okapi
- func (o *Okapi) WithReadTimeout(seconds int) *Okapi
- func (o *Okapi) WithRenderer(renderer Renderer) *Okapi
- func (o *Okapi) WithRendererConfig(config TemplateConfig) *Okapi
- func (o *Okapi) WithRendererFromDirectory(dir string, extensions ...string) *Okapi
- func (o *Okapi) WithRendererFromFS(fsys fs.FS, pattern string) *Okapi
- func (o *Okapi) WithSimpleProblemDetailErrorHandler() *Okapi
- func (o *Okapi) WithStrictSlash(strict bool) *Okapi
- func (o *Okapi) WithWriteTimeout(seconds int) *Okapi
- type OneOfExpr
- type OpenAPI
- type OptionFunc
- func WithAccessLogDisabled() OptionFunc
- func WithAddr(addr string) OptionFunc
- func WithContext(ctx context.Context) OptionFunc
- func WithCors(cors Cors) OptionFunc
- func WithDebug() OptionFunc
- func WithDefaultErrorHandler() OptionFunc
- func WithErrorHandler(handler ErrorHandler) OptionFunc
- func WithIdleTimeout(t int) OptionFunc
- func WithLogger(logger *slog.Logger) OptionFunc
- func WithMaxMultipartMemory(max int64) OptionFunc
- func WithMuxRouter(router *mux.Router) OptionFunc
- func WithOpenAPIDisabled() OptionFunc
- func WithPort(port int) OptionFunc
- func WithProblemDetailErrorHandler(config *ErrorHandlerConfig) OptionFunc
- func WithReadTimeout(t int) OptionFunc
- func WithRenderer(renderer Renderer) OptionFunc
- func WithServer(server *http.Server) OptionFunc
- func WithSimpleProblemDetailErrorHandler() OptionFunc
- func WithStrictSlash(strict bool) OptionFunc
- func WithTLS(tlsConfig *tls.Config) OptionFunc
- func WithTLSServer(addr string, tlsConfig *tls.Config) OptionFunc
- func WithWriteTimeout(t int) OptionFunc
- type OrExpr
- type Origin
- type PrefixExpr
- type ProblemDetail
- type Renderer
- type RendererFunc
- type ResponseWriter
- type Route
- func (r *Route) Deprecated() *Route
- func (r *Route) Disable() *Route
- func (r *Route) Enable() *Route
- func (r *Route) Hide() *Route
- func (r *Route) Use(m ...Middleware)
- func (r *Route) WithIO(req any, res any) *Route
- func (r *Route) WithInput(req any) *Route
- func (r *Route) WithOutput(res any) *Route
- func (r *Route) WithSecurity(security ...map[string][]string) *Route
- type RouteDefinition
- type RouteOption
- func Deprecated() RouteOption
- func Description(description string) RouteOption
- func DocBasicAuth() RouteOption
- func DocBearerAuth() RouteOption
- func DocDeprecated() RouteOption
- func DocDescription(description string) RouteOption
- func DocErrorResponse(status int, v any) RouteOption
- func DocHeader(name, typ, desc string, required bool) RouteOption
- func DocHeaderWithDefault(name, typ, desc string, required bool, defvalue any) RouteOption
- func DocHide() RouteOption
- func DocOperationId(operationId string) RouteOption
- func DocPathParam(name, typ, desc string) RouteOption
- func DocPathParamWithDefault(name, typ, desc string, defvalue any) RouteOption
- func DocQueryParam(name, typ, desc string, required bool) RouteOption
- func DocQueryParamWithDefault(name, typ, desc string, required bool, defvalue any) RouteOption
- func DocRequestBody(v any) RouteOption
- func DocResponse(statusOrValue any, vOptional ...any) RouteOption
- func DocResponseHeader(name, typ string, desc ...string) RouteOption
- func DocSummary(summary string) RouteOption
- func DocTag(tag string) RouteOption
- func DocTags(tags ...string) RouteOption
- func Hide() RouteOption
- func OperationId(operationId string) RouteOption
- func Request(v any) RouteOption
- func Response(v any) RouteOption
- func Summary(summary string) RouteOption
- func Tag(tag string) RouteOption
- func Tags(tags ...string) RouteOption
- func UseMiddleware(m ...Middleware) RouteOption
- func WithIO(req any, res any) RouteOption
- type Router
- type SchemaInfo
- type SecurityRequirement
- type SecurityScheme
- type SecuritySchemes
- type SendFunc
- type Serializer
- type Server
- type Servers
- type Store
- type StreamOptions
- type Template
- type TemplateConfig
- type TestServer
- type TestingT
- type TextSerializer
- type ValidationError
- type ValidationErrorResponse
Constants ¶
This section is empty.
Variables ¶
var (
ErrNoRenderer = errors.New("no renderer set for context")
)
Functions ¶
func DefaultErrorHandler ¶ added in v0.4.0
DefaultErrorHandler provides the standard error response format
func GenerateJwtToken ¶
GenerateJwtToken generates a JWT with custom claims and expiry
func IsClientError ¶ added in v0.0.5
IsClientError checks if the status code is a 4xx client error.
func IsServerError ¶ added in v0.0.5
IsServerError checks if the status code is a 5xx server error.
func LoadTLSConfig ¶ added in v0.0.3
LoadTLSConfig creates a TLS configuration from certificate and key files Parameters:
- certFile: Path to the certificate file (PEM format)
- keyFile: Path to the private key file (PEM format)
- caFile: Optional path to CA certificate file for client verification (set to "" to disable)
- clientAuth: Whether to require client certificate verification
Returns:
- *tls.Config configured with the certificate and settings
- error if any occurred during loading
func RegisterRoutes ¶ added in v0.0.13
func RegisterRoutes(o *Okapi, routes []RouteDefinition)
RegisterRoutes registers a slice of RouteDefinition with the given Okapi instance.
For each route definition, this function determines whether to register the route on the root Okapi instance or within a specific route group (if provided).
It supports all standard HTTP methods (GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS) and applies any associated RouteOptions, such as documentation annotations or middleware settings.
If the Group field in the RouteDefinition is nil, the route is registered on the root Okapi instance. Otherwise, it is registered within the specified group. If the group's Okapi reference is unset, it is automatically assigned from the root instance.
The function panics if an unsupported HTTP method is encountered.
Note: Use the `Use()` method on either the Okapi instance or a Group to apply middleware.
Example:
routes := []okapi.RouteDefinition{
{
Method: "GET",
Path: "/example",
Handler: exampleHandler,
OperationId: "get-example",
Summary: "Example GET request",
Request: nil,
Response: &ExampleResponse{},
Group: &okapi.Group{Prefix: "/api/v1", Tags: []string{"Example"}},
},
{
Method: "POST",
Path: "/example",
Handler: exampleHandler,
Middlewares: []okapi.Middleware{customMiddleware}
Options: []okapi.RouteOption{
okapi.DocSummary("Example POST request"),
okapi.Request(&ExampleRequest{}),
okapi.Response(&ExampleResponse{}),
},
Security: Security: []map[string][]string{
{
"bearerAuth": {},
},
},
},
}
// Create a new Okapi instance
app := okapi.New()
okapi.RegisterRoutes(app, routes)
func ValidateAddr ¶
ValidateAddr checks if the entrypoint address is valid. A valid entrypoint address should be in the format ":<port>" or "<IP>:<port>", where <IP> is a valid IP address and <port> is a valid port number (1-65535).
Types ¶
type AndExpr ¶ added in v0.0.12
type AndExpr struct {
Left Expression
Right Expression
}
func And ¶ added in v0.0.12
func And(left, right Expression) *AndExpr
type Base64Serializer ¶ added in v0.2.1
type Base64Serializer struct{}
Base64Serializer for binary data
type BasicAuth ¶ added in v0.0.9
type BasicAuth struct {
Username string
Password string
Realm string
ContextKey string // where to store the username e.g. "user", default(username)
}
BasicAuth provides basic authentication for routes.
func (*BasicAuth) Middleware ¶ added in v0.0.9
func (b *BasicAuth) Middleware(next HandlerFunc) HandlerFunc
Middleware is a basic authentication middleware that checks Basic Auth credentials. It returns 401 Unauthorized and sets the WWW-Authenticate header on failure.
type BasicAuthMiddleware ¶
type BasicAuthMiddleware BasicAuth
BasicAuthMiddleware provides basic authentication for routes
deprecated, use BasicAuth
func (*BasicAuthMiddleware) Middleware ¶
func (b *BasicAuthMiddleware) Middleware(next HandlerFunc) HandlerFunc
Middleware
deprecate, use BasicAuth.Middleware
type BodyLimit ¶
type BodyLimit struct {
MaxBytes int64
}
BodyLimit is a middleware that limits the size of the request body.
func (BodyLimit) Middleware ¶
func (b BodyLimit) Middleware(next HandlerFunc) HandlerFunc
Middleware is a middleware that limits the size of the request body to prevent excessive memory usage.
type Contact ¶ added in v0.0.5
type Contact struct {
Extensions map[string]any `json:"-" yaml:"-"` // Custom extensions not part of OpenAPI spec
Name string `json:"name,omitempty" yaml:"name,omitempty"` // Optional contact name
URL string `json:"url,omitempty" yaml:"url,omitempty"` // Optional contact URL
Email string `json:"email,omitempty" yaml:"email,omitempty"` // Optional contact email
}
Contact contains contact information for the API maintainers
type ContainsExpr ¶ added in v0.0.12
ContainsExpr checks if claim contains substring or array contains value
func Contains ¶ added in v0.0.12
func Contains(claimKey string, values ...string) *ContainsExpr
type Context ¶
type Context struct {
// contains filtered or unexported fields
}
func NewContext ¶ added in v0.1.2
NewContext creates a new Okapi Context
func NewTestContext ¶ added in v0.1.2
NewTestContext creates a Context with its own in-memory request and recorder. Unlike NewContext, it does not initialize a default Okapi engine.
func (*Context) Abort ¶ added in v0.0.2
Abort writes a standardized 500 Internal Server Error response.
func (*Context) AbortBadGateway ¶ added in v0.0.5
AbortBadGateway writes a standardized 502 Bad Gateway response.
func (*Context) AbortBadRequest ¶ added in v0.0.2
AbortBadRequest writes a standardized 400 Bad request response.
func (*Context) AbortConflict ¶ added in v0.0.2
AbortConflict writes a standardized 409 Conflict response.
func (*Context) AbortExpectationFailed ¶ added in v0.0.5
AbortExpectationFailed writes a standardized 417 Expectation Failed response.
func (*Context) AbortFailedDependency ¶ added in v0.0.5
AbortFailedDependency writes a standardized 424 Failed Dependency response.
func (*Context) AbortForbidden ¶ added in v0.0.2
AbortForbidden writes a standardized 403 Forbidden response.
func (*Context) AbortGatewayTimeout ¶ added in v0.0.5
AbortGatewayTimeout writes a standardized 504 Gateway Timeout response.
func (*Context) AbortHTTPVersionNotSupported ¶ added in v0.0.5
AbortHTTPVersionNotSupported writes a standardized 505 HTTP version Not Supported response.
func (*Context) AbortInsufficientStorage ¶ added in v0.0.5
AbortInsufficientStorage writes a standardized 507 Insufficient Storage response.
func (*Context) AbortInternalServerError ¶ added in v0.0.5
AbortInternalServerError writes a standardized 500 Internal Server Error response.
func (*Context) AbortLengthRequired ¶ added in v0.0.5
AbortLengthRequired writes a standardized 411 Length Required response.
func (*Context) AbortLocked ¶ added in v0.0.5
AbortLocked writes a standardized 423 Locked response.
func (*Context) AbortLoopDetected ¶ added in v0.0.5
AbortLoopDetected writes a standardized 508 Loop Detected response.
func (*Context) AbortMethodNotAllowed ¶ added in v0.0.5
AbortMethodNotAllowed writes a standardized 405 Method Not Allowed response.
func (*Context) AbortMisdirectedRequest ¶ added in v0.0.5
AbortMisdirectedRequest writes a standardized 421 Misdirected request response.
func (*Context) AbortNetworkAuthenticationRequired ¶ added in v0.0.5
AbortNetworkAuthenticationRequired writes a standardized 511 Network Authentication Required response.
func (*Context) AbortNotAcceptable ¶ added in v0.0.5
AbortNotAcceptable writes a standardized 406 Not Acceptable response.
func (*Context) AbortNotExtended ¶ added in v0.0.5
AbortNotExtended writes a standardized 510 Not Extended response.
func (*Context) AbortNotFound ¶ added in v0.0.2
AbortNotFound writes a standardized 404 Not Found response.
func (*Context) AbortNotImplemented ¶ added in v0.0.5
AbortNotImplemented writes a standardized 501 Not Implemented response.
func (*Context) AbortNotModified ¶ added in v0.3.4
AbortNotModified writes a standardized 304 Not Modified response.
func (*Context) AbortPaymentRequired ¶ added in v0.0.5
AbortPaymentRequired writes a standardized 402 Payment Required response.
func (*Context) AbortPreconditionFailed ¶ added in v0.0.5
AbortPreconditionFailed writes a standardized 412 Precondition Failed response.
func (*Context) AbortPreconditionRequired ¶ added in v0.0.5
AbortPreconditionRequired writes a standardized 428 Precondition Required response.
func (*Context) AbortProxyAuthRequired ¶ added in v0.0.5
AbortProxyAuthRequired writes a standardized 407 Proxy Authentication Required response.
func (*Context) AbortRequestEntityTooLarge ¶ added in v0.0.5
AbortRequestEntityTooLarge writes a standardized 413 request Entity Too Large response.
func (*Context) AbortRequestHeaderFieldsTooLarge ¶ added in v0.0.5
AbortRequestHeaderFieldsTooLarge writes a standardized 431 request Header Fields Too Large response.
func (*Context) AbortRequestTimeout ¶ added in v0.0.5
AbortRequestTimeout writes a standardized 408 request Timeout response.
func (*Context) AbortRequestURITooLong ¶ added in v0.0.5
AbortRequestURITooLong writes a standardized 414 request-URI Too Long response.
func (*Context) AbortRequestedRangeNotSatisfiable ¶ added in v0.0.5
AbortRequestedRangeNotSatisfiable writes a standardized 416 Requested Range Not Satisfiable response.
func (*Context) AbortServiceUnavailable ¶ added in v0.0.5
AbortServiceUnavailable writes a standardized 503 Service Unavailable response.
func (*Context) AbortTeapot ¶ added in v0.0.5
AbortTeapot writes a standardized 418 I'm a teapot response.
func (*Context) AbortTooEarly ¶ added in v0.0.5
AbortTooEarly writes a standardized 425 Too Early response.
func (*Context) AbortTooManyRequests ¶ added in v0.0.2
AbortTooManyRequests writes a standardized 429 Too Many Requests response.
func (*Context) AbortUnauthorized ¶ added in v0.0.2
AbortUnauthorized writes a standardized 401 Unauthorized response.
func (*Context) AbortUnavailableForLegalReasons ¶ added in v0.0.5
AbortUnavailableForLegalReasons writes a standardized 451 Unavailable For Legal Reasons response.
func (*Context) AbortUnsupportedMediaType ¶ added in v0.0.5
AbortUnsupportedMediaType writes a standardized 415 Unsupported Media Type response.
func (*Context) AbortUpgradeRequired ¶ added in v0.0.5
AbortUpgradeRequired writes a standardized 426 Upgrade Required response.
func (*Context) AbortValidationError ¶ added in v0.0.2
AbortValidationError writes a standardized 422 Unprocessable Entity response.
func (*Context) AbortValidationErrors ¶ added in v0.0.5
func (c *Context) AbortValidationErrors(errors []ValidationError, msg ...string) error
AbortValidationErrors writes a detailed validation error response. Note: This method always uses the default ValidationErrorResponse structure regardless of custom error handlers, as it has a specific format for validation errors.
func (*Context) AbortValidationErrorsWithProblemDetail ¶ added in v0.4.0
func (c *Context) AbortValidationErrorsWithProblemDetail(errors []ValidationError, msg ...string) error
AbortValidationErrorsWithProblemDetail writes validation errors as RFC 7807 Problem Details
func (*Context) AbortVariantAlsoNegotiates ¶ added in v0.0.5
AbortVariantAlsoNegotiates writes a standardized 506 Variant Also Negotiates response.
func (*Context) AbortWithError ¶
AbortWithError writes a standardized error response using the configured error handler.
func (*Context) AbortWithJSON ¶ added in v0.0.2
AbortWithJSON writes a custom JSON error response.
func (*Context) AbortWithProblemDetail ¶ added in v0.4.0
func (c *Context) AbortWithProblemDetail(problem *ProblemDetail) error
AbortWithProblemDetail writes an RFC 7807 Problem Details response.
func (*Context) AbortWithStatus ¶ added in v0.0.2
AbortWithStatus writes an error response with status code and custom message. Note: This method maintains backward compatibility by using the default ErrorResponse structure. For full customization, use AbortWithError or set a custom ErrorHandler.
func (*Context) AcceptLanguage ¶
AcceptLanguage returns the Accept-Language header values as a slice. Trims whitespace from each language tag.
func (*Context) Bind ¶
Bind populates the given struct with request data by inspecting tags and content type. It supports two binding styles:
**Flat binding (legacy style)** Request body fields (JSON, XML, YAML, Protobuf, Form) can be mixed directly with query parameters, headers, cookies, and path params in a single struct.
**Body field binding (recommended style)** A struct may contain a dedicated `Body` field (or tagged as `body`) that represents the request payload, while sibling fields represent query params, headers, cookies, and path params. This style enforces a clear separation between metadata and body.
Validation tags such as `required`, `min`, `max`, `minLength`, and `maxLength` are supported, along with descriptive metadata (`description`) that can be used for documentation.
Example (Body field binding):
type BookInput struct {
// Query parameter
Tags []string `query:"tags" description:"List of book tags"`
// Header parameter
Accept string `header:"Accept" required:"true" description:"Accept header"`
// Cookie parameter
SessionID string `cookie:"SessionID" required:"true" description:"Session ID cookie"`
// Path parameter
BookID string `path:"bookId" required:"true" description:"Book ID"`
// Request body
Body struct {
Name string `json:"name" required:"true" minLength:"2" maxLength:"100" description:"Book name"`
Price int `json:"price" required:"true" min:"5" max:"100" yaml:"price" description:"Book price"`
}
}
okapi.Put("/books/:bookId", func(c okapi.Context) error {
book := &BookInput{}
if err := c.Bind(book); err != nil {
return c.AbortBadRequest("Invalid input", err)
}
return c.Respond(book)
})
func (*Context) BindMultipart ¶
BindMultipart binds multipart form data to the provided struct.
func (*Context) ContentType ¶
ContentType returns the Content-Type header value.
func (*Context) Context ¶ added in v0.3.5
Context returns the context.Context associated with the current request.
func (*Context) Cookie ¶
Cookie retrieves a cookie value by name. Returns empty string and error if cookie not found.
func (*Context) ErrorBadGateway ¶ added in v0.0.5
ErrorBadGateway writes a 502 Bad Gateway response.
func (*Context) ErrorBadRequest ¶ added in v0.0.2
ErrorBadRequest writes a 400 Bad request response.
func (*Context) ErrorConflict ¶ added in v0.0.2
ErrorConflict writes a 409 Conflict response.
func (*Context) ErrorExpectationFailed ¶ added in v0.0.5
ErrorExpectationFailed writes a 417 Expectation Failed response.
func (*Context) ErrorFailedDependency ¶ added in v0.0.5
ErrorFailedDependency writes a 424 Failed Dependency response.
func (*Context) ErrorForbidden ¶ added in v0.0.2
ErrorForbidden writes a 403 Forbidden response.
func (*Context) ErrorGatewayTimeout ¶ added in v0.0.5
ErrorGatewayTimeout writes a 504 Gateway Timeout response.
func (*Context) ErrorHTTPVersionNotSupported ¶ added in v0.0.5
ErrorHTTPVersionNotSupported writes a 505 HTTP version Not Supported response.
func (*Context) ErrorInsufficientStorage ¶ added in v0.0.5
ErrorInsufficientStorage writes a 507 Insufficient Storage response.
func (*Context) ErrorInternalServerError ¶ added in v0.0.2
ErrorInternalServerError writes a 500 Internal Server Error response.
func (*Context) ErrorLengthRequired ¶ added in v0.0.5
ErrorLengthRequired writes a 411 Length Required response.
func (*Context) ErrorLocked ¶ added in v0.0.5
ErrorLocked writes a 423 Locked response.
func (*Context) ErrorLoopDetected ¶ added in v0.0.5
ErrorLoopDetected writes a 508 Loop Detected response.
func (*Context) ErrorMethodNotAllowed ¶ added in v0.0.5
ErrorMethodNotAllowed writes a 405 Method Not Allowed response.
func (*Context) ErrorMisdirectedRequest ¶ added in v0.0.5
ErrorMisdirectedRequest writes a 421 Misdirected request response.
func (*Context) ErrorNetworkAuthenticationRequired ¶ added in v0.0.5
ErrorNetworkAuthenticationRequired writes a 511 Network Authentication Required response.
func (*Context) ErrorNotAcceptable ¶ added in v0.0.5
ErrorNotAcceptable writes a 406 Not Acceptable response.
func (*Context) ErrorNotExtended ¶ added in v0.0.5
ErrorNotExtended writes a 510 Not Extended response.
func (*Context) ErrorNotFound ¶ added in v0.0.2
ErrorNotFound writes a 404 Not Found response.
func (*Context) ErrorNotImplemented ¶ added in v0.0.5
ErrorNotImplemented writes a 501 Not Implemented response.
func (*Context) ErrorNotModified ¶ added in v0.3.4
ErrorNotModified writes a 304 Not Modified response.
func (*Context) ErrorPaymentRequired ¶ added in v0.0.5
ErrorPaymentRequired writes a 402 Payment Required response.
func (*Context) ErrorPreconditionFailed ¶ added in v0.0.5
ErrorPreconditionFailed writes a 412 Precondition Failed response.
func (*Context) ErrorPreconditionRequired ¶ added in v0.0.5
ErrorPreconditionRequired writes a 428 Precondition Required response.
func (*Context) ErrorProxyAuthRequired ¶ added in v0.0.5
ErrorProxyAuthRequired writes a 407 Proxy Authentication Required response.
func (*Context) ErrorRequestEntityTooLarge ¶ added in v0.0.5
ErrorRequestEntityTooLarge writes a 413 request Entity Too Large response.
func (*Context) ErrorRequestHeaderFieldsTooLarge ¶ added in v0.0.5
ErrorRequestHeaderFieldsTooLarge writes a 431 request Header Fields Too Large response.
func (*Context) ErrorRequestTimeout ¶ added in v0.0.5
ErrorRequestTimeout writes a 408 request Timeout response.
func (*Context) ErrorRequestURITooLong ¶ added in v0.0.5
ErrorRequestURITooLong writes a 414 request-URI Too Long response.
func (*Context) ErrorRequestedRangeNotSatisfiable ¶ added in v0.0.5
ErrorRequestedRangeNotSatisfiable writes a 416 Requested Range Not Satisfiable response.
func (*Context) ErrorServiceUnavailable ¶ added in v0.0.2
ErrorServiceUnavailable writes a 503 Service Unavailable response.
func (*Context) ErrorTeapot ¶ added in v0.0.5
ErrorTeapot writes a 418 I'm a teapot response (RFC 2324).
func (*Context) ErrorTooEarly ¶ added in v0.0.5
ErrorTooEarly writes a 425 Too Early response.
func (*Context) ErrorTooManyRequests ¶ added in v0.0.2
ErrorTooManyRequests writes a 429 Too Many Requests response.
func (*Context) ErrorUnauthorized ¶ added in v0.0.2
ErrorUnauthorized writes a 401 Unauthorized response.
func (*Context) ErrorUnavailableForLegalReasons ¶ added in v0.0.5
ErrorUnavailableForLegalReasons writes a 451 Unavailable For Legal Reasons response.
func (*Context) ErrorUnprocessableEntity ¶ added in v0.0.2
ErrorUnprocessableEntity writes a 422 Unprocessable Entity response.
func (*Context) ErrorUnsupportedMediaType ¶ added in v0.0.5
ErrorUnsupportedMediaType writes a 415 Unsupported Media Type response.
func (*Context) ErrorUpgradeRequired ¶ added in v0.0.5
ErrorUpgradeRequired writes a 426 Upgrade Required response.
func (*Context) ErrorVariantAlsoNegotiates ¶ added in v0.0.5
ErrorVariantAlsoNegotiates writes a 506 Variant Also Negotiates response.
func (*Context) FormFile ¶
func (c *Context) FormFile(key string) (*multipart.FileHeader, error)
FormFile retrieves a file from multipart form data. Returns the file and any error encountered.
func (*Context) Get ¶
Get retrieves a value from the context's data store with thread-safe access. Returns the value and a boolean indicating if the key exists.
func (*Context) GetBool ¶
GetBool retrieves a boolean value from the context. Returns false if key doesn't exist or value isn't a bool.
func (*Context) GetInt ¶
GetInt retrieves an integer value from the context. Returns 0 if key doesn't exist or value isn't an int.
func (*Context) GetInt64 ¶
GetInt64 retrieves an int64 value from the context. Returns 0 if key doesn't exist or value isn't an int64.
func (*Context) GetString ¶
GetString retrieves a string value from the context. Returns empty string if key doesn't exist or value isn't a string.
func (*Context) HTMLView ¶
HTMLView renders an HTML template from a string with the given status code.
func (*Context) IsWebSocketUpgrade ¶
IsWebSocketUpgrade checks if the request is a WebSocket upgrade request.
func (*Context) Logger ¶ added in v0.0.15
Logger returns the logger instance associated with the Okapi context.
func (*Context) MaxMultipartMemory ¶
MaxMultipartMemory returns the maximum memory for multipart form
func (*Context) NoContent ¶ added in v0.4.0
NoContent returns an empty response body with status code 204
func (*Context) Query ¶
Query retrieves a URL query parameter value. Returns empty string if parameter doesn't exist.
func (*Context) QueryArray ¶ added in v0.1.0
QueryArray retrieves all values for a query parameter. Supports both repeated params (?tags=a&tags=b) and comma-separated (?tags=a,b).
func (*Context) QueryMap ¶
QueryMap returns all query parameters as a map. Only includes the first value for each parameter.
func (*Context) Respond ¶ added in v0.1.0
Respond serializes the output struct into the HTTP response. It inspects struct tags to automatically set headers, cookies, and status code, and encodes the response body in the format requested by the `Accept` header.
Supported formats: JSON, XML, YAML, plain text, HTML.
Example:
type BookResponse struct {
Status int // HTTP status code
version string `header:"version"` // Response header
Session string `cookie:"SessionID"` // Response cookie
Body struct {
ID int `json:"id"`
Name string `json:"name"`
Price int `json:"price"`
}
}
okapi.Get("/books/:id", func(c okapi.Context) error {
return c.Respond(BookResponse{
version: "v1",
Session: "abc123",
Status: 200,
Body: struct {
ID int `json:"id"`
Name string `json:"name"`
Price int `json:"price"`
}{
ID: 1, Name: "Okapi Guide", Price: 50,
},
})
})
func (*Context) Response ¶
func (c *Context) Response() ResponseWriter
Response returns the http.ResponseWriter for writing responses. This is an alias for ResponseWriter for convenience.
func (*Context) ResponseWriter ¶ added in v0.0.14
func (c *Context) ResponseWriter() http.ResponseWriter
ResponseWriter returns the http.ResponseWriter for writing responses.
func (*Context) Return ¶ added in v0.1.0
Return is an alias for Respond to improve readability when sending output.
func (*Context) SSESendBinary ¶ added in v0.2.1
SSESendBinary sends binary data as base64
func (*Context) SSESendData ¶ added in v0.2.1
SSESendData sends structured data as JSON
func (*Context) SSESendEvent ¶ added in v0.2.1
SSESendEvent writes SSE response with an ID.
func (*Context) SSESendJSON ¶ added in v0.2.1
SSESendJSON sends JSON data with explicit JSON serialization
func (*Context) SSESendText ¶ added in v0.2.1
SSESendText sends plain text data
func (*Context) SSEStreamWithOptions ¶ added in v0.2.1
func (c *Context) SSEStreamWithOptions(ctx context.Context, messageChan <-chan Message, opts *StreamOptions) error
SSEStreamWithOptions provides advanced streaming control
func (*Context) SendSSECustom ¶ added in v0.2.1
func (c *Context) SendSSECustom(data any, serializer Serializer) error
SendSSECustom sends data with custom serializer
func (*Context) SendSSEvent ¶ added in v0.0.18
SendSSEvent writes SSE response with an ID. Deprecated: use SSESendEvent instead.
func (*Context) ServeFileAttachment ¶
ServeFileAttachment serves a file as an attachment (download).
func (*Context) ServeFileFromFS ¶
func (c *Context) ServeFileFromFS(filepath string, fs http.FileSystem)
ServeFileFromFS serves a file from a custom http.FileSystem.
func (*Context) ServeFileInline ¶
ServeFileInline serves a file to be displayed inline in the browser.
func (*Context) Set ¶
Set stores a value in the context's data store with thread-safe access. Initializes the data map if it doesn't exist.
func (*Context) SetCookie ¶
func (c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool)
SetCookie sets a cookie with various configurable options. Defaults path to "/" if empty.
func (*Context) SetErrorHandler ¶ added in v0.4.0
func (c *Context) SetErrorHandler(handler ErrorHandler)
SetErrorHandler allows setting a custom error handler at the context level This overrides the global error handler for this specific request
func (*Context) SetMaxMultipartMemory ¶ added in v0.0.7
SetMaxMultipartMemory sets the maximum memory for multipart form (default: 32 MB)
func (*Context) ShouldBind ¶
ShouldBind is a convenience method that binds request data to a struct and returns a boolean indicating success.
func (*Context) WriteStatus ¶
WriteStatus writes the HTTP status code to the response.
type Cors ¶ added in v0.0.2
type Cors struct {
// AllowedOrigins specifies which origins are allowed.
AllowedOrigins []string
// AllowedHeaders defines which request headers are permitted.
AllowedHeaders []string
// ExposeHeaders indicates which response headers are exposed to the client.
ExposeHeaders []string
//
Headers map[string]string
// MaxAge defines how long the results of a preflight request can be cached (in seconds).
MaxAge int
// AllowMethods lists the HTTP methods permitted for cross-origin requests.
AllowMethods []string
AllowCredentials bool
}
func (Cors) CORSHandler ¶ added in v0.0.2
func (cors Cors) CORSHandler(next HandlerFunc) HandlerFunc
CORSHandler applies CORS headers and handles preflight (OPTIONS) requests.
type DocBuilder ¶ added in v0.0.6
type DocBuilder struct {
// contains filtered or unexported fields
}
DocBuilder helps construct a list of RouteOption functions in a fluent, chainable way.
func Doc ¶ added in v0.0.6
func Doc() *DocBuilder
Doc creates and returns a new DocBuilder instance for chaining documentation options.
func (*DocBuilder) AsOption ¶ added in v0.0.6
func (b *DocBuilder) AsOption() RouteOption
AsOption returns a single RouteOption by merging all accumulated documentation options. This is functionally equivalent to Build(), and exists for naming flexibility and readability.
You can use either Build() or AsOption(), depending on what best fits your code style.
Example:
okapi.Get("/books", handler, okapi.Doc().response(Book{}).AsOption())
func (*DocBuilder) BearerAuth ¶ added in v0.0.6
func (b *DocBuilder) BearerAuth() *DocBuilder
BearerAuth marks the route as requiring Bearer token authentication.
func (*DocBuilder) Build ¶ added in v0.0.6
func (b *DocBuilder) Build() RouteOption
Build returns a single RouteOption composed of all accumulated documentation options. This method is intended to be passed directly to route registration functions.
Example:
okapi.Get("/books", handler, okapi.Doc().response(Book{}).Summary("List books").Build())
func (*DocBuilder) Deprecated ¶ added in v0.0.8
func (b *DocBuilder) Deprecated() *DocBuilder
Deprecated marks the route as deprecated
func (*DocBuilder) Description ¶ added in v0.0.13
func (b *DocBuilder) Description(description string) *DocBuilder
Description adds a description to the route documentation.
func (*DocBuilder) ErrorResponse ¶ added in v0.0.7
func (b *DocBuilder) ErrorResponse(status int, v any) *DocBuilder
ErrorResponse defines an error response schema for a specific HTTP status code in the route's OpenAPI documentation. Deprecated: This function is deprecated in favor of Response(status, v).
Parameters:
- status: the HTTP status code (e.g., 400, 404, 500).
- v: a Go value (e.g., a struct instance) whose type will be used to generate the OpenAPI schema for the error response.
func (*DocBuilder) Header ¶ added in v0.0.6
func (b *DocBuilder) Header(name, typ, desc string, required bool) *DocBuilder
Header adds a documented header to the route. name: header name typ: header value type (e.g., "string", "int") desc: header description required: whether the header is required
func (*DocBuilder) HeaderWithDefault ¶ added in v0.1.0
func (b *DocBuilder) HeaderWithDefault(name, typ, desc string, required bool, defvalue any) *DocBuilder
HeaderWithDefault adds a documented header to the route with default. name: header name typ: header value type (e.g., "string", "int") desc: header description required: whether the header is required defvalue: default value to use
func (*DocBuilder) Hide ¶ added in v0.0.19
func (b *DocBuilder) Hide() *DocBuilder
Hide marks the route to be excluded from OpenAPI documentation.
func (*DocBuilder) OperationId ¶ added in v0.0.19
func (b *DocBuilder) OperationId(operationId string) *DocBuilder
OperationId sets a unique identifier for the operation in the OpenAPI documentation.
func (*DocBuilder) PathParam ¶ added in v0.0.6
func (b *DocBuilder) PathParam(name, typ, desc string) *DocBuilder
PathParam adds a documented path parameter to the route. name: parameter name typ: parameter type (e.g., "string", "int") desc: parameter description
func (*DocBuilder) PathParamWithDefault ¶ added in v0.1.1
func (b *DocBuilder) PathParamWithDefault(name, typ, desc string, defvalue any) *DocBuilder
PathParamWithDefault adds a documented path parameter to the route. name: parameter name typ: parameter type (e.g., "string", "int") desc: parameter description defvalue: default value to use
func (*DocBuilder) QueryParam ¶ added in v0.0.6
func (b *DocBuilder) QueryParam(name, typ, desc string, required bool) *DocBuilder
QueryParam adds a documented query parameter to the route. name: parameter name typ: parameter type (e.g., "string", "int") desc: parameter description required: whether the parameter is required
func (*DocBuilder) QueryParamWithDefault ¶ added in v0.1.0
func (b *DocBuilder) QueryParamWithDefault(name, typ, desc string, required bool, defvalue any) *DocBuilder
QueryParamWithDefault adds a documented query parameter to the route with default. name: parameter name typ: parameter type (e.g., "string", "int") desc: parameter description required: whether the parameter is required defvalue: default value to use
func (*DocBuilder) RequestBody ¶ added in v0.0.6
func (b *DocBuilder) RequestBody(v any) *DocBuilder
RequestBody adds a request body schema to the route documentation using the provided value.
func (*DocBuilder) Response ¶ added in v0.0.6
func (b *DocBuilder) Response(statusOrValue any, vOptional ...any) *DocBuilder
Response registers a response schema for the route's OpenAPI documentation. It can be used in two ways:
- DocResponse(status int, value any) - Defines a response schema for the specified HTTP status code (e.g., 200, 201, 400).
- DocResponse(value any) - Shorthand for DocResponse(200, value).
Examples:
DocResponse(201, CreatedResponse{}) // Response for 201 Created
DocResponse(400, ErrorResponse{}) // Response for 400 Bad Request
DocResponse(Response{}) // Response: assumes status 200
func (*DocBuilder) ResponseHeader ¶ added in v0.0.13
func (b *DocBuilder) ResponseHeader(name, typ string, desc ...string) *DocBuilder
ResponseHeader adds a response header to the route documentation name: header name typ: header value type (e.g., "string", "int") desc: header description, optional
func (*DocBuilder) Summary ¶ added in v0.0.6
func (b *DocBuilder) Summary(summary string) *DocBuilder
Summary adds a short summary description to the route documentation.
func (*DocBuilder) Tags ¶ added in v0.0.6
func (b *DocBuilder) Tags(tags ...string) *DocBuilder
Tags adds one or more tags to the route documentation for categorization.
type EqualsExpr ¶ added in v0.0.12
EqualsExpr checks if claim equals expected value
func Equals ¶ added in v0.0.12
func Equals(claimKey, expected string) *EqualsExpr
type ErrorFormat ¶ added in v0.4.0
type ErrorFormat string
ErrorFormat defines the format for error responses
const ( // ErrorFormatDefault uses the standard ErrorResponse format ErrorFormatDefault ErrorFormat = "default" // ErrorFormatProblemJSON uses RFC 7807 Problem Details (application/problem+json) ErrorFormatProblemJSON ErrorFormat = "problem+json" // ErrorFormatProblemXML uses RFC 7807 Problem Details (application/problem+xml) ErrorFormatProblemXML ErrorFormat = "problem+xml" )
type ErrorHandler ¶ added in v0.4.0
ErrorHandler is a function type that formats error responses
func ProblemDetailErrorHandler ¶ added in v0.4.0
func ProblemDetailErrorHandler(config *ErrorHandlerConfig) ErrorHandler
ProblemDetailErrorHandler creates an error handler that returns RFC 7807 Problem Details
type ErrorHandlerConfig ¶ added in v0.4.0
type ErrorHandlerConfig struct {
// Format specifies the error response format
Format ErrorFormat
// TypePrefix is the base URI for problem types (e.g., "https://api.example.com/errors/")
TypePrefix string
IncludeInstance bool
IncludeTimestamp bool
// CustomFields allows adding custom fields to all error responses
CustomFields map[string]any
}
ErrorHandlerConfig configures the error handler behavior
type ErrorResponse ¶ added in v0.0.2
type ErrorResponse struct {
Code int `json:"code"`
Message string `json:"message"`
Details string `json:"details,omitempty"`
Timestamp time.Time `json:"timestamp"`
}
ErrorResponse represents a standardized error response structure
type Expression ¶ added in v0.0.12
Expression types for claims validation
func ParseExpression ¶ added in v0.0.12
func ParseExpression(input string) (Expression, error)
type ExpressionParser ¶ added in v0.0.12
type ExpressionParser struct {
// contains filtered or unexported fields
}
type ExternalDocs ¶ added in v0.0.19
type ExternalDocs struct {
Extensions map[string]any `json:"-" yaml:"-"`
Origin *Origin `json:"__origin__,omitempty" yaml:"__origin__,omitempty"`
Description string `json:"description,omitempty" yaml:"description,omitempty"`
URL string `json:"url,omitempty" yaml:"url,omitempty"`
}
func (*ExternalDocs) ToOpenAPI ¶ added in v0.0.19
func (e *ExternalDocs) ToOpenAPI() *openapi3.ExternalDocs
type Group ¶
type Group struct {
// Prefix is the base path for all routes in this group.
Prefix string
// Tags is an optional tag for the group, used for documentation purposes.
Tags []string
// contains filtered or unexported fields
}
func NewGroup ¶ added in v0.0.13
func NewGroup(basePath string, okapi *Okapi, middlewares ...Middleware) *Group
func (*Group) Delete ¶
func (g *Group) Delete(path string, h HandlerFunc, opts ...RouteOption) *Route
Delete registers a DELETE route within the group with the given path and handler.
func (*Group) Deprecated ¶ added in v0.0.12
Deprecated marks the Group as deprecated for its routes. Returns the Group to allow method chaining.
func (*Group) Disable ¶ added in v0.0.6
Disable marks the Group as disabled, causing all routes within it to return 404 Not Found. Returns the Group to allow method chaining.
func (*Group) Enable ¶ added in v0.0.6
Enable marks the Group as enabled, allowing all routes within it to handle requests normally. Returns the Group to allow method chaining.
func (*Group) Get ¶
func (g *Group) Get(path string, h HandlerFunc, opts ...RouteOption) *Route
Get registers a GET route within the group with the given path and handler.
func (*Group) Group ¶
func (g *Group) Group(path string, middlewares ...Middleware) *Group
Group creates a nested subgroup with an additional path segment and optional middlewares. The new group inherits all middlewares from its parent group.
func (*Group) HandleHTTP ¶ added in v0.0.9
func (g *Group) HandleHTTP(method, path string, h http.Handler, opts ...RouteOption)
HandleHTTP registers a standard http.Handler and wraps it with the group's middleware chain.
func (*Group) HandleStd ¶ added in v0.0.9
func (g *Group) HandleStd(method, path string, h func(http.ResponseWriter, *http.Request), opts ...RouteOption)
HandleStd registers a standard http.HandlerFunc and wraps it with the group's middleware chain.
func (*Group) Head ¶
func (g *Group) Head(path string, h HandlerFunc, opts ...RouteOption) *Route
Head registers a HEAD route within the group with the given path and handler.
func (*Group) Options ¶
func (g *Group) Options(path string, h HandlerFunc, opts ...RouteOption) *Route
Options registers an OPTIONS route within the group with the given path and handler.
func (*Group) Patch ¶
func (g *Group) Patch(path string, h HandlerFunc, opts ...RouteOption) *Route
Patch registers a PATCH route within the group with the given path and handler.
func (*Group) Post ¶
func (g *Group) Post(path string, h HandlerFunc, opts ...RouteOption) *Route
Post registers a POST route within the group with the given path and handler.
func (*Group) Put ¶
func (g *Group) Put(path string, h HandlerFunc, opts ...RouteOption) *Route
Put registers a PUT route within the group with the given path and handler.
func (*Group) Register ¶ added in v0.0.13
func (g *Group) Register(routes ...RouteDefinition)
Register registers a slice of RouteDefinition with the group. It ensures that each route is associated with the group and its Okapi instance. If a route's Group field is nil, it assigns the current group to it. If the route's Group's Okapi reference is nil, it assigns the group's Okapi instance to it. This method is useful for bulk registering routes defined in a controller or similar structure.
Example:
routes := []okapi.RouteDefinition{
{
Method: "GET",
Path: "/example",
Handler: exampleHandler,
Options: []okapi.RouteOption{
okapi.DocSummary("Example GET request"),
},
},
{
Method: "POST",
Path: "/example",
Handler: exampleHandler,
Options: []okapi.RouteOption{
okapi.DocSummary("Example POST request"),
},
},
}
// Create a new Okapi instance
app := okapi.New()
api:= app.Group("/api")
api.Register(routes...)
func (*Group) Use ¶
func (g *Group) Use(m ...Middleware)
Use adds one or more middlewares to the group's middleware chain. These middlewares will be executed in the order they are added, before the route handler for all routes within this group. Middlewares are inherited by any subgroups created from this group.
func (*Group) UseMiddleware ¶ added in v0.0.9
UseMiddleware registers a standard HTTP middleware function and integrates it into Okapi's middleware chain.
This enables compatibility with existing middleware libraries that use the func(http.Handler) http.Handler pattern.
func (*Group) WithBasicAuth ¶ added in v0.0.18
func (*Group) WithBearerAuth ¶ added in v0.0.10
WithBearerAuth marks the Group as requiring Bearer authentication for its routes. Returns the Group to allow method chaining.
func (*Group) WithSecurity ¶ added in v0.0.18
WithSecurity sets the security requirements for the Group's routes.
type HandlerFunc ¶ added in v0.1.3
HandlerFunc is a function type that takes a Context and returns an error.
func H ¶ added in v0.4.0
func H[I any](h func(*Context, *I) error) HandlerFunc
H is a shorthand alias for Handle. It provides the same behavior and is intended for more concise route definitions when readability is preferred over verbosity.
Example:
o.Post("/books", okapi.H(func(c *okapi.Context, in *Book) error {
return c.Created(in)
}))
func Handle ¶ added in v0.4.0
func Handle[I any](h func(*Context, *I) error) HandlerFunc
Handle binds and validates the request body into the input type I, then executes the handler.
This helper is useful when you only need to process the request input and control the response manually inside the handler (e.g. using c.OK(), c.JSON(), c.NoContent(), etc.).
Example:
o.Post("/books", okapi.Handle(func(c *okapi.Context, in *Book) error {
return c.Created(in)
}))
func HandleIO ¶ added in v0.4.0
func HandleIO[I any, O any](h func(*Context, *I) (*O, error)) HandlerFunc
HandleIO binds and validates the request body into the input type I, then executes the handler and writes the response based on content negotiation.
The response format is determined by the Accept request header: - application/json -> JSON response - application/xml -> XML response - text/html -> HTML response (if template registered) - etc.
This is useful for APIs that need to support multiple response formats without writing separate handlers.
Example:
type Book struct {
ID int `json:"id"`
Name string `json:"name" form:"name" maxLength:"50" example:"The Go Programming Language" yaml:"name" required:"true"`
Price int `json:"price" form:"price" query:"price" yaml:"price" min:"0" default:"0" max:"500"`
Qty int `json:"qty" form:"qty" query:"qty" yaml:"qty" default:"0"`
Status string `json:"status" form:"status" query:"status" yaml:"status" enum:"paid,unpaid,canceled" required:"true" example:"available"`
}
type BookOutput struct {
Status int
Body Book
}
o.Post("/books", okapi.HandleIO(func(c *okapi.Context, in *Book) (*BookOutput, error) {
books = append(books, *in)
return &BookOutput{Body: *in}, nil
}))
// Client requests with Accept: application/json -> JSON response
// Client requests with Accept: application/xml -> XML response
func HandleO ¶ added in v0.4.0
func HandleO[O any](h func(*Context) (*O, error)) HandlerFunc
HandleO executes the handler and writes the response based on content negotiation. Useful for GET/LIST endpoints that don't need input binding but support multiple response formats.
Example:
type BooksOutput struct {
Status int
Body []Book
}
o.Get("/books", okapi.HandleO(func(c *okapi.Context) (*BooksOutput, error) {
return &BooksOutput{Body: books}, nil
}))
// Client can request JSON, XML, HTML, etc. via Accept header
func LoggerMiddleware ¶
func LoggerMiddleware(next HandlerFunc) HandlerFunc
LoggerMiddleware is a middleware that logs request details like method, URL, client IP, status, duration, referer, and user agent.
type JSONSerializer ¶ added in v0.2.1
type JSONSerializer struct{}
JSONSerializer is the default JSON serializer
type JWTAuth ¶
type JWTAuth struct {
// SecretKey is a legacy secret key used for HMAC algorithms (e.g., HS256).
// Deprecated: Use SigningSecret instead.
SecretKey []byte
// SigningSecret is the key used for signing/validating tokens when using symmetric algorithms like HS256.
SigningSecret []byte
// JwksFile provides a static JWKS (JSON Web Key Set), either from a file or base64-encoded string.
// Use okapi.LoadJWKSFromFile() to load the JWKS from a file.
// Optional.
JwksFile *Jwks
// JwksUrl specifies a remote JWKS endpoint URL for key discovery.
// Optional.
JwksUrl string
// Audience is the expected "aud" (audience) claim in the token.
// Optional.
Audience string
// Issuer is the expected "iss" (issuer) claim in the token.
// Optional.
Issuer string
// RsaKey is a public RSA key used to verify tokens signed with RS256.
// Optional.
RsaKey *rsa.PublicKey
// Algo specifies the expected signing algorithm (e.g., "RS256", "HS256").
// Optional.
Algo string
// TokenLookup defines how and where to extract the token from the request.
// Supported formats include:
// - "header:Authorization" (default)
// - "query:token"
// - "cookie:jwt"
TokenLookup string
// ContextKey is the key used to store the full validated JWT claims in the request context.
//
// Use this when you need access to the entire set of claims for advanced processing or custom logic
// within your handler or middleware.
//
// If you only need specific claim values (e.g., "user.email", "user.id"), consider using ForwardClaims instead.
//
// Example:
// ContextKey: "user"
ContextKey string
// ForwardClaims maps context keys to JWT claim paths (supports dot notation for nested fields).
// This extracts selected claims and stores them in the request context under the specified keys.
//
// Use this when you want to expose only specific claims to handlers or middleware, without
// needing access to the entire token.
//
// Example:
// ForwardClaims: map[string]string{
// "email": "user.email",
// "uid": "user.id",
// }
ForwardClaims map[string]string
// ClaimsExpression defines a custom expression to validate JWT claims.
// Useful for enforcing advanced conditions on claims such as role, scope, or custom fields.
//
// Supported functions:
// - Equals(field, value)
// - Prefix(field, prefix)
// - Contains(field, val1, val2, ...)
// - OneOf(field, val1, val2, ...)
//
// Logical Operators:
// - ! — NOT
// - && — AND (evaluated before OR)
// - || — OR (evaluated after AND)
//
// These operators allow you to combine multiple expressions to create complex validation logic.
// Example:
// jwtAuth.ClaimsExpression = "Equals(`email_verified`, `true`) && OneOf(`user.role`, `admin`, `owner`) && Contains(`tags`, `vip`, `premium`)"
//
// In the above:
// - The expression ensures the user is verified AND either has an admin/owner role,
// OR belongs to a premium tag group.
ClaimsExpression string
// ValidateClaims is an optional custom validation function for processing JWT claims.
// This provides full control over claim validation logic and can be used alongside or
// instead of ClaimsExpression.
//
// Return an error to reject the request.
//
// Example:
// ValidateClaims: func(c *okapi.Context,claims jwt.Claims) error {
// mapClaims, ok := claims.(jwt.MapClaims)
// if !ok {
// return errors.New("invalid claims type")
// }
// if emailVerified, _ := mapClaims["email_verified"].(bool); !emailVerified {
// return errors.New("email not verified")
// }
// if role, _ := mapClaims["role"].(string); role != "admin" {
// return errors.New("unauthorized role")
// }
// return nil
// }
ValidateClaims func(c *Context, claims jwt.Claims) error
// This includes scenarios such as missing, expired, malformed, or invalid tokens,
// or when claims validation (via ClaimsExpression or ValidateClaims) is unsuccessful.
//
// Use this to customize the error response sent to unauthorized clients.
OnUnauthorized HandlerFunc
// Deprecated: Use ValidateClaims instead.
//
// ValidateRole was previously used for role-based access control, but has been
// replaced by the more general ValidateClaims function which allows for flexible
// validation of any JWT claims.
ValidateRole func(claims jwt.Claims) error
// contains filtered or unexported fields
}
JWTAuth is a configuration struct for JWT-based authentication middleware.
You must configure at least one token verification mechanism: - SigningSecret: for HMAC algorithms - RsaKey: for RSA algorithms (e.g. RS256) - JwksUrl: to fetch public keys dynamically from a JWKS endpoint - JwksFile: to load static JWKS from a file or base64 string, use okapi.LoadJWKSFromFile()
Fields: JWTAuth holds configuration for JWT-based authentication.
func (*JWTAuth) Middleware ¶
func (jwtAuth *JWTAuth) Middleware(next HandlerFunc) HandlerFunc
Middleware validates JWT tokens from the configured source
type Jwks ¶ added in v0.0.9
type Jwks struct {
Keys []Jwk `json:"keys"`
}
func LoadJWKSFromFile ¶ added in v0.0.9
LoadJWKSFromFile loads a JWKS (JSON Web Key Set) from a file path or a base64-encoded string.
If the input is a base64-encoded string, it decodes it. Otherwise, it treats the input as a file path and attempts to open and read it. The function returns a parsed *Jwks struct or an error if any step fails.
type License ¶ added in v0.0.5
type License struct {
Extensions map[string]any `json:"-" yaml:"-"` // Custom extensions not part of OpenAPI spec
Name string `json:"name" yaml:"name"` // Required license name (e.g., "MIT")
URL string `json:"url,omitempty" yaml:"url,omitempty"` // Optional URL to the license
}
License contains license information for the API. It follows the OpenAPI specification format.
type Location ¶ added in v0.0.19
type Logger ¶
type Logger struct {
}
Logger is a middleware that logs request details such as method, URL, client IP, status, duration, referer, and user agent.
type Message ¶
type Message struct {
// ID unique identifier for the message
ID string `json:"id"`
// Event type
Event string `json:"event"`
// Data payload
Data any `json:"message"`
// Retry interval
Retry uint `json:"retry,omitempty"`
// Serializer to use for the message
Serializer Serializer `json:"-"`
}
Message represents a Server-Sent Events (SSE) message.
type Middleware ¶
type Middleware func(next HandlerFunc) HandlerFunc
type NotExpr ¶ added in v0.0.12
type NotExpr struct {
Expr Expression
}
func Not ¶ added in v0.0.12
func Not(expr Expression) *NotExpr
type OAuthFlow ¶ added in v0.0.18
type OAuthFlows ¶ added in v0.0.18
type OAuthFlows struct {
Implicit *OAuthFlow
Password *OAuthFlow
ClientCredentials *OAuthFlow
AuthorizationCode *OAuthFlow
}
func (*OAuthFlows) ToOpenAPI ¶ added in v0.0.18
func (flows *OAuthFlows) ToOpenAPI() *openapi3.OAuthFlows
type Okapi ¶
type Okapi struct {
// contains filtered or unexported fields
}
Okapi represents the core application structure of the framework, holding configuration, routers, middleware, server settings, and documentation components.
func New ¶
func New(options ...OptionFunc) *Okapi
New creates a new Okapi instance with the provided options.
func (*Okapi) Any ¶
func (o *Okapi) Any(path string, h HandlerFunc, opts ...RouteOption) *Route
Any registers a route that matches any HTTP method with the given path and handler function. Returns the created *Route for possible chaining or modification.
Useful for handlers that need to respond to multiple HTTP methods uniformly.
Example:
o.Any("/health", func(c okapi.Context) error {
return c.String(200, "OK")
})
func (*Okapi) Delete ¶
func (o *Okapi) Delete(path string, h HandlerFunc, opts ...RouteOption) *Route
Delete registers a new DELETE route with the given path and handler function. Returns the created *Route for possible chaining or modification.
Commonly used for removing resources.
Example:
o.Delete("/users/{id}", func(c okapi.Context) error {
id := c.Param("id")
// Delete user logic...
return c.NoContent(204)
})
func (*Okapi) DisableAccessLog ¶ added in v0.0.4
func (*Okapi) Get ¶
func (o *Okapi) Get(path string, h HandlerFunc, opts ...RouteOption) *Route
Get registers a new GET route with the given path and handler function. Returns the created *Route for possible chaining or modification.
Path parameters support type hints for OpenAPI documentation generation:
- /users/{id} or /users/:id -> "id" documented as UUID in OpenAPI
- /users/{user_id} -> "user_id" documented as UUID in OpenAPI
- /users/{id:int} or /users/:id:int -> "id" documented as integer in OpenAPI
- /users/{user_id:uuid} -> "user_id" documented as UUID in OpenAPI
Note: Type hints affect OpenAPI schema generation only. All parameters are accessed as strings via Context.Param() at runtime.
Example:
o.Get("/users/{id:int}", func(c okapi.Context) error {
userID := c.Param("id") // Returns string "123"
return c.JSON(200, okapi.M{"user_id": userID})
})
func (*Okapi) GetContext ¶
GetContext returns the current context
func (*Okapi) Group ¶
func (o *Okapi) Group(prefix string, middlewares ...Middleware) *Group
Group creates a new route group with the specified base path and optional middlewares. The group inherits all existing middlewares from the parent Okapi instance. Routes registered within the group will have their paths prefixed with the group's path, and the group's middlewares will be executed before the route-specific handlers.
Panics if the path is empty, as this would lead to ambiguous routing.
Example:
api := okapi.Group("/api", AuthMiddleware) // All /api routes require auth
api.Get("/users", getUserHandler) // Handles /api/users
api.Post("/users", createUserHandler) // Handles /api/users
func (*Okapi) Handle ¶ added in v0.0.4
func (o *Okapi) Handle(method, path string, h HandlerFunc, opts ...RouteOption)
Handle registers a new route with the given HTTP method, path, and Okapi-style handler function.
It performs the following steps:
- Normalizes the route path
- Creates and configures a new Route instance
- Applies all registered middleware to the handler
- Registers the route with the underlying router (with method filtering)
- Adds centralized error handling for the route
Parameters:
- method: HTTP method (e.g., "GET", "POST", "PUT")
- path: URL path pattern (supports path parameters, e.g., /users/:id)
- h: A handler function using Okapi's Context abstraction
- opts: Optional route metadata (e.g., OpenAPI summary, description, tags)
Middleware:
All middleware registered via Use() or UseMiddleware() will be applied in order, wrapping around the handler.
Error Handling:
Any non-nil error returned by the handler will automatically result in a 500 Internal Server Error response.
Example:
okapi.Handle("GET", "/users/:id", func(c *okapi.Context) error {
id := c.Param("id")
// process request...
return nil
})
func (*Okapi) HandleHTTP ¶ added in v0.0.8
func (o *Okapi) HandleHTTP(method, path string, h http.Handler, opts ...RouteOption)
HandleHTTP registers a new route using a standard http.Handler.
It wraps the provided http.Handler into Okapi's internal HandlerFunc signature and processes it as if it were registered via Handle.
Parameters:
- method: HTTP method (e.g., "GET", "POST", "DELETE")
- path: URL path pattern (supports dynamic segments)
- h: A standard http.Handler (or http.HandlerFunc)
- opts: Optional route metadata (e.g., OpenAPI summary, description, tags)
Differences from Handle:
- Uses the standard http.Handler interface
- Middleware is still applied
- Errors must be handled inside the handler itself (Okapi will not capture them)
Example:
okapi.HandleHTTP("GET", "/static", http.FileServer(http.Dir("./public")))
func (*Okapi) HandleStd ¶ added in v0.0.8
func (o *Okapi) HandleStd(method, path string, h func(http.ResponseWriter, *http.Request), opts ...RouteOption)
HandleStd is a convenience method for registering handlers using the standard http.HandlerFunc signature (func(http.ResponseWriter, *http.Request)).
Internally, it wraps the handler into http.Handler and delegates to HandleHTTP.
Example:
okapi.HandleStd("GET", "/greet", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello from Okapi!"))
})
This handler will still benefit from:
- All registered middleware
- Automatic route and CORS registration
func (*Okapi) Head ¶
func (o *Okapi) Head(path string, h HandlerFunc, opts ...RouteOption) *Route
Head registers a new HEAD route with the given path and handler function. Returns the created *Route for possible chaining or modification.
Identical to GET but without the response body, useful for checking resource existence or metadata.
func (*Okapi) NoMethod ¶ added in v0.0.10
func (o *Okapi) NoMethod(h HandlerFunc)
NoMethod sets a custom handler to be executed when the HTTP method is not allowed.
This function is triggered when the request path exists but the method (e.g., POST, GET) is not allowed. It enables you to define a consistent response for unsupported HTTP methods (405).
Example:
o.NoMethod(func(c okapi.Context) error {
return c.AbortMethodNotAllowed("Custom 405 - Method Not Allowed")
})
func (*Okapi) NoRoute ¶ added in v0.0.10
func (o *Okapi) NoRoute(h HandlerFunc)
NoRoute sets a custom handler to be executed when no matching route is found.
This function allows you to define a fallback handler for unmatched routes (404). It is useful for returning custom error pages or JSON responses when a route doesn't exist.
Example:
o.NoRoute(func(c okapi.Context) error {
return c.AbortNotFound("Custom 404 - Not found")
})
func (*Okapi) Options ¶
func (o *Okapi) Options(path string, h HandlerFunc, opts ...RouteOption) *Route
Options registers a new OPTIONS route with the given path and handler function. Returns the created *Route for possible chaining or modification.
Commonly used for CORS preflight requests to describe communication options.
func (*Okapi) Patch ¶
func (o *Okapi) Patch(path string, h HandlerFunc, opts ...RouteOption) *Route
Patch registers a new PATCH route with the given path and handler function. Returns the created *Route for possible chaining or modification.
Commonly used for partial updates to resources.
Example:
o.Patch("/users/{id}", func(c okapi.Context) error {
id := c.Param("id")
var updates map[string]any
if err := c.Bind(&updates); err != nil {
return err
}
// Partial update logic...
return c.JSON(200, updates)
})
func (*Okapi) Post ¶
func (o *Okapi) Post(path string, h HandlerFunc, opts ...RouteOption) *Route
Post registers a new POST route with the given path and handler function. Returns the created *Route for possible chaining or modification.
Commonly used for creating resources. The handler can access request body via Context.Bind() or Context.Body().
Example:
o.Post("/users", func(c okapi.Context) error {
var user User
if err := c.Bind(&user); err != nil {
return err
}
// Create user logic...
return c.Created(user)
})
func (*Okapi) Put ¶
func (o *Okapi) Put(path string, h HandlerFunc, opts ...RouteOption) *Route
Put registers a new PUT route with the given path and handler function. Returns the created *Route for possible chaining or modification.
Commonly used for replacing/updating entire resources.
Example:
o.Put("/users/{id}", func(c okapi.Context) error {
id := c.Param("id")
var user User
if err := c.Bind(&user); err != nil {
return err
}
// Update user logic...
return c.JSON(200, user)
})
func (*Okapi) Register ¶ added in v0.0.13
func (o *Okapi) Register(routes ...RouteDefinition)
Register registers a list of RouteDefinition to the Okapi instance. This method allows you to define multiple routes in a single call, which can be useful for organizing your routes in a more structured way. Example:
routes := []okapi.RouteDefinition{
{
Method: "POST",
Path: "/example",
Handler: exampleHandler,
Middlewares: []okapi.Middleware{customMiddleware}
OperationId: "PostExample",
Summary: "Example POST request",
Description: "This endpoint handles example POST request.",
Request: &RequestExample{},
Response: &ResponseExample{}
},
{
Method: "GET",
Path: "/example",
Handler: exampleHandler,
Options: []okapi.RouteOption{
okapi.DocSummary("Example GET request"),
},
Security: Security: []map[string][]string{
{
"bearerAuth": {},
},
},
},
}
// Create a new Okapi instance
app := okapi.New()
app.Register(routes...)
func (*Okapi) RegisterSchemas ¶ added in v0.1.1
func (o *Okapi) RegisterSchemas(schemas map[string]*SchemaInfo) error
RegisterSchemas registers component schemas that are re-used as references.
func (*Okapi) ServeHTTP ¶
func (o *Okapi) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements the http.Handler interface
func (*Okapi) SetContext ¶
func (*Okapi) Shutdown ¶
Shutdown performs graceful shutdown of the provided server using a background context Deprecated, please use StopCtx
func (*Okapi) StartForTest ¶ added in v0.1.3
StartForTest starts the Okapi server for testing and returns the base URL.
func (*Okapi) StartServer ¶
StartServer starts the Okapi server with the specified HTTP server
func (*Okapi) StaticFS ¶
func (o *Okapi) StaticFS(prefix string, fs http.FileSystem)
StaticFS serves static files from a custom http.FileSystem (e.g., embed.FS).
func (*Okapi) StaticFile ¶
StaticFile serves a single file at the specified path.
func (*Okapi) StopWithContext ¶ added in v0.3.1
StopWithContext gracefully shuts down all active Okapi servers with the provided context.
func (*Okapi) Use ¶
func (o *Okapi) Use(middlewares ...Middleware)
Use registers one or more middleware functions to the Okapi instance. These middleware will be executed in the order they are added for every request before reaching the route handler. Middleware added here will apply to all routes registered on this Okapi instance and any groups created from it.
Middleware functions have the signature:
func(next HandlerFunc) HandlerFunc
Example:
// Add logging and authentication middleware okapi.Use(LoggingMiddleware, AuthMiddleware)
Note: For group-specific middleware, use Group.Use() instead.
func (*Okapi) UseMiddleware ¶ added in v0.0.8
UseMiddleware registers a standard HTTP middleware function and integrates it into Okapi's middleware chain.
This enables compatibility with existing middleware libraries that use the func(http.Handler) http.Handler pattern.
Example:
okapi.UseMiddleware(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.request) {
w.Header().Set("X-Powered-By", "Okapi")
next.ServeHTTP(w, r)
})
})
Internally, Okapi converts between http.Handler and HandlerFunc to allow smooth interop.
func (*Okapi) WaitForServer ¶ added in v0.1.3
WaitForServer waits until the server is ready and returns the address
func (*Okapi) With ¶
func (o *Okapi) With(options ...OptionFunc) *Okapi
With applies the provided options to the Okapi instance
func (*Okapi) WithContext ¶ added in v0.3.1
WithContext sets the context for the Okapi instance
func (*Okapi) WithDefaultErrorHandler ¶ added in v0.4.0
WithDefaultErrorHandler sets the default error handler
func (*Okapi) WithDefaultRenderer ¶ added in v0.3.2
WithDefaultRenderer sets renderer from default file pattern
func (*Okapi) WithErrorHandler ¶ added in v0.4.0
func (o *Okapi) WithErrorHandler(handler ErrorHandler) *Okapi
WithErrorHandler sets a custom error handler
func (*Okapi) WithIdleTimeout ¶ added in v0.0.4
func (*Okapi) WithMaxMultipartMemory ¶ added in v0.0.7
func (*Okapi) WithOpenAPIDisabled ¶ added in v0.0.10
WithOpenAPIDisabled disabled OpenAPI Docs
func (*Okapi) WithOpenAPIDocs ¶ added in v0.0.4
WithOpenAPIDocs registers the OpenAPI JSON and Swagger UI handlers at the configured PathPrefix (default: /docs).
UI Path: /docs JSON Path: /openapi.json
func (*Okapi) WithProblemDetailErrorHandler ¶ added in v0.4.0
func (o *Okapi) WithProblemDetailErrorHandler(config *ErrorHandlerConfig) *Okapi
WithProblemDetailErrorHandler sets RFC 7807 Problem Details error handler
func (*Okapi) WithReadTimeout ¶ added in v0.0.4
func (*Okapi) WithRenderer ¶ added in v0.0.10
WithRenderer sets a custom Renderer for the server.
This allows you to define how templates or views are rendered in response handlers. You can implement the Renderer interface on your own type, or use the built-in RendererFunc adapter to provide an inline function.
Example using a custom Renderer type:
type Template struct {
templates *template.Template
}
func (t *Template) Render(w io.Writer, name string, data interface{}, c okapi.Context) error {
return t.templates.ExecuteTemplate(w, name, data)
}
o := okapi.New().WithRenderer(&Template{templates: template.Must(template.ParseGlob("public/views/*.html"))})
Example using RendererFunc:
o := okapi.New().WithRenderer(okapi.RendererFunc(func(w io.Writer,
name string, data interface{}, c *okapi.Context) error {
tmpl, err := template.ParseFiles("public/views/" + name + ".html")
if err != nil {
return err
}
return tmpl.ExecuteTemplate(w, name, data)
}))
func (*Okapi) WithRendererConfig ¶ added in v0.3.2
func (o *Okapi) WithRendererConfig(config TemplateConfig) *Okapi
WithRendererConfig sets renderer using configuration
func (*Okapi) WithRendererFromDirectory ¶ added in v0.3.2
WithRendererFromDirectory sets renderer from directory
func (*Okapi) WithRendererFromFS ¶ added in v0.3.2
WithRendererFromFS sets renderer from embedded filesystem
func (*Okapi) WithSimpleProblemDetailErrorHandler ¶ added in v0.4.0
WithSimpleProblemDetailErrorHandler sets RFC 7807 Problem Details with default config
func (*Okapi) WithStrictSlash ¶ added in v0.0.4
func (*Okapi) WithWriteTimeout ¶ added in v0.0.4
type OpenAPI ¶ added in v0.0.4
type OpenAPI struct {
Title string // Title of the API
Version string // Version of the API
Servers Servers // List of server URLs where the API is hosted
License License // License information for the API
Contact Contact // Contact information for the API maintainers
// SecuritySchemes defines security schemes for the OpenAPI specification.
SecuritySchemes SecuritySchemes
ExternalDocs *ExternalDocs
ComponentSchemas map[string]*SchemaInfo
}
OpenAPI contains configuration for generating OpenAPI/Swagger documentation. It includes metadata about the API and its documentation.
func (OpenAPI) ToOpenAPISpec ¶ added in v0.0.5
ToOpenAPISpec converts OpenAPI to *openapi3.T. It transforms the custom OpenAPI configuration to a complete OpenAPI specification object.
type OptionFunc ¶
type OptionFunc func(*Okapi)
func WithAccessLogDisabled ¶
func WithAccessLogDisabled() OptionFunc
WithAccessLogDisabled disables access logging
func WithContext ¶ added in v0.3.0
func WithContext(ctx context.Context) OptionFunc
WithContext sets the default context for the Okapi instance
func WithCors ¶ added in v0.0.2
func WithCors(cors Cors) OptionFunc
WithCors returns an OptionFunc that configures CORS settings
func WithDefaultErrorHandler ¶ added in v0.4.0
func WithDefaultErrorHandler() OptionFunc
WithDefaultErrorHandler sets the default error handler (useful for resetting)
func WithErrorHandler ¶ added in v0.4.0
func WithErrorHandler(handler ErrorHandler) OptionFunc
WithErrorHandler sets a custom error handler for the application
func WithIdleTimeout ¶ added in v0.0.3
func WithIdleTimeout(t int) OptionFunc
WithIdleTimeout returns an OptionFunc that sets the idle timeout
func WithLogger ¶
func WithLogger(logger *slog.Logger) OptionFunc
WithLogger sets the logger for the Okapi instance
func WithMaxMultipartMemory ¶ added in v0.0.7
func WithMaxMultipartMemory(max int64) OptionFunc
WithMaxMultipartMemory Maximum memory for multipart forms
func WithMuxRouter ¶ added in v0.0.10
func WithMuxRouter(router *mux.Router) OptionFunc
WithMuxRouter sets the router for the Okapi instance
func WithOpenAPIDisabled ¶ added in v0.0.5
func WithOpenAPIDisabled() OptionFunc
WithOpenAPIDisabled disabled OpenAPI Docs
func WithProblemDetailErrorHandler ¶ added in v0.4.0
func WithProblemDetailErrorHandler(config *ErrorHandlerConfig) OptionFunc
WithProblemDetailErrorHandler sets RFC 7807 Problem Details error handler
func WithReadTimeout ¶ added in v0.0.3
func WithReadTimeout(t int) OptionFunc
WithReadTimeout returns an OptionFunc that sets the read timeout
func WithRenderer ¶ added in v0.0.10
func WithRenderer(renderer Renderer) OptionFunc
WithRenderer sets a custom Renderer for the server.
This allows you to define how templates or views are rendered in response handlers. You can implement the Renderer interface on your own type, or use the built-in RendererFunc adapter to provide an inline function.
Example using a custom Renderer type:
type Template struct {
templates *template.Template
}
func (t *Template) Render(w io.Writer, name string, data interface{}, c okapi.Context) error {
return t.templates.ExecuteTemplate(w, name, data)
}
o := okapi.New().WithRenderer(&Template{templates: template.Must(template.ParseGlob("public/views/*.html"))})
Example using RendererFunc:
o := okapi.New().WithRenderer(okapi.RendererFunc(func(w io.Writer,
name string, data interface{}, c *okapi.Context) error {
tmpl, err := template.ParseFiles("public/views/" + name + ".html")
if err != nil {
return err
}
return tmpl.ExecuteTemplate(w, name, data)
}))
func WithServer ¶
func WithServer(server *http.Server) OptionFunc
WithServer sets the HTTP server for the Okapi instance
func WithSimpleProblemDetailErrorHandler ¶ added in v0.4.0
func WithSimpleProblemDetailErrorHandler() OptionFunc
WithSimpleProblemDetailErrorHandler sets RFC 7807 Problem Details with default config
func WithStrictSlash ¶
func WithStrictSlash(strict bool) OptionFunc
WithStrictSlash sets whether to enforce strict slash handling
func WithTLS ¶ added in v0.0.4
func WithTLS(tlsConfig *tls.Config) OptionFunc
WithTLS sets tls config to HTTP Server for the Okapi instance
Use okapi.LoadTLSConfig() to create a TLS configuration from certificate and key files
func WithTLSServer ¶
func WithTLSServer(addr string, tlsConfig *tls.Config) OptionFunc
WithTLSServer sets the TLS server for the Okapi instance
Use okapi.LoadTLSConfig() to create a TLS configuration from certificate and key files
func WithWriteTimeout ¶ added in v0.0.3
func WithWriteTimeout(t int) OptionFunc
WithWriteTimeout returns an OptionFunc that sets the write timeout
type OrExpr ¶ added in v0.0.12
type OrExpr struct {
Left Expression
Right Expression
}
func Or ¶ added in v0.0.12
func Or(left, right Expression) *OrExpr
type Origin ¶ added in v0.0.19
type PrefixExpr ¶ added in v0.0.12
PrefixExpr checks if claim starts with prefix
func Prefix ¶ added in v0.0.12
func Prefix(claimKey, prefix string) *PrefixExpr
type ProblemDetail ¶ added in v0.4.0
type ProblemDetail struct {
Type string `json:"type" xml:"type"`
Title string `json:"title" xml:"title"`
Status int `json:"status" xml:"status"`
Detail string `json:"detail,omitempty" xml:"detail,omitempty"`
Instance string `json:"instance,omitempty" xml:"instance,omitempty"`
Extensions map[string]any `json:"-" xml:"-"`
}
ProblemDetail represents RFC 7807 Problem Details for HTTP APIs See: https://tools.ietf.org/html/rfc7807
func NewProblemDetail ¶ added in v0.4.0
func NewProblemDetail(code int, typeURI, detail string) *ProblemDetail
NewProblemDetail creates a new ProblemDetail with common defaults
func (ProblemDetail) MarshalJSON ¶ added in v0.4.0
func (p ProblemDetail) MarshalJSON() ([]byte, error)
MarshalJSON implements custom JSON marshaling to include extensions
func (*ProblemDetail) WithExtension ¶ added in v0.4.0
func (p *ProblemDetail) WithExtension(key string, value any) *ProblemDetail
WithExtension adds a custom extension field
func (*ProblemDetail) WithInstance ¶ added in v0.4.0
func (p *ProblemDetail) WithInstance(instance string) *ProblemDetail
WithInstance adds an instance URI to the problem detail
func (*ProblemDetail) WithTimestamp ¶ added in v0.4.0
func (p *ProblemDetail) WithTimestamp() *ProblemDetail
WithTimestamp adds a timestamp extension
type RendererFunc ¶
type ResponseWriter ¶ added in v0.1.0
type ResponseWriter interface {
http.ResponseWriter
// StatusCode returns the written status code, or 0 if not written.
StatusCode() int
// BytesWritten returns number of bytes written to the body.
BytesWritten() int
// Close closes the writer if supported. Returns error instead of hiding it.
Close() error
// Hijack upgrades to raw TCP if supported (WebSockets, proxy, etc).
Hijack() (net.Conn, *bufio.ReadWriter, error)
// Flush flushes buffered data if supported (streaming, SSE, gzip, etc).
Flush()
// Push initiates HTTP/2 server push if supported.
Push(string, *http.PushOptions) error
}
ResponseWriter extends http.ResponseWriter with additional utilities.
type Route ¶
type Route struct {
Name string
Path string
Method string
// contains filtered or unexported fields
}
Route defines the structure of a registered HTTP route in the framework. It includes metadata used for routing, OpenAPI documentation, and middleware handling.
func (*Route) Deprecated ¶ added in v0.0.15
Deprecated marks the Route as deprecated. Returns the Route to allow method chaining.
func (*Route) Disable ¶ added in v0.0.6
Disable marks the Route as disabled, causing it to return 404 Not Found. Returns the Route to allow method chaining.
func (*Route) Enable ¶ added in v0.0.6
Enable marks the Route as enabled, allowing it to handle requests normally. Returns the Route to allow method chaining.
func (*Route) Hide ¶ added in v0.0.19
Hide marks the Route as hidden, preventing it from being listed in OpenAPI documentation.
func (*Route) Use ¶ added in v0.0.15
func (r *Route) Use(m ...Middleware)
Use registers one or more middleware functions to the Route.
func (*Route) WithIO ¶ added in v0.1.0
WithIO sets both the input (request) and output (response) schemas for the route. This is a convenience method that combines WithInput and WithOutput in a single call. Both parameters are optional: pass nil if you only want one side.
Example:
route.WithIO(CreateBookInput{}, BookResponse{})
func (*Route) WithInput ¶ added in v0.1.0
WithInput sets the input (request) schema for the route. The value should be a struct or pointer to a struct with binding tags (query, path, header, cookie, form, body). If provided, Okapi will:
- Bind incoming request data to the struct
- Validate based on struct tags
- Generate OpenAPI documentation for the request schema
func (*Route) WithOutput ¶ added in v0.1.0
WithOutput sets the output (response) schema for the route. The value can be any type (struct, slice, map, etc.). If provided, Okapi will:
- Serialize the value into the response body
- Generate OpenAPI documentation for the response schema
type RouteDefinition ¶ added in v0.0.13
type RouteDefinition struct {
// Method is the HTTP method for the route (e.g., GET, POST, PUT, DELETE, etc.)
Method string
// Path is the URL path for the route, relative to the base path of the Okapi instance or group
Path string
// Handler is the function that will handle requests to this route
Handler HandlerFunc
// Group attach Route to a Group // Optional
Group *Group
// OperationId is an optional unique identifier for the route, primarily
// used in OpenAPI documentation to distinguish operations.
OperationId string
// Summary is an optional short description of the route,
// used for OpenAPI documentation.
// Example: "Create a new book"
Summary string
// Description is an optional detailed description of the route,
// used for OpenAPI documentation.
// Example: "This endpoint allows clients to create a new book in the system by providing the necessary details."
Description string
// Tags sets the tags for the Route, which can be used for documentation purposes. // Optional
Tags []string
// Request optionally defines the expected input schema for the route.
// It can be a struct or pointer to a struct with binding tags (query, path, header, cookie, form, body).
// If provided, Okapi will:
// - Bind incoming request data to the struct
// - Perform validations based on struct tags (e.g., required, minLength, maxLength, default)
// - Generate OpenAPI documentation for the request schema
//
// Note: To generate OpenAPI documentation, it is recommended to use a struct or pointer to a struct.
//
// Example:
// type CreateBookInput struct {
// Tags []string `query:"tags"`
// XApiKey string `header:"X-API-KEY" required:"true" description:"API Key"`
// Body struct {
// Title string `json:"title" required:"true" minLength:"5" maxLength:"100" description:"Book title"`
// Price int `json:"price" max:"5" min:"2" yaml:"price" required:"true" description:"Book price"`
// }
// }
// RouteDefinition{
// Method: "POST",
// Path: "/books",
// Request: &CreateBookInput{},
// }
Request any
// Response optionally defines the output schema for the route.
// It can be any type (struct, slice, map, etc.). If provided, Okapi will:
// - Serialize the value into the response body (e.g., JSON)
// - Generate OpenAPI documentation for the response schema
//
// Note: To generate OpenAPI documentation, it is recommended to use a struct or pointer to a struct.
//
// Example:
// type BookResponse struct {
// ID string `json:"id"`
// Title string `json:"title"`
// }
// RouteDefinition{
// Method: "POST",
// Path: "/books",
// Request: &CreateBookInput{},
// Response: &BookResponse{},
// }
Response any
// Security defines the security requirements for the route, such as authentication schemes // Optional
// It can be also applied at Group level.
Security []map[string][]string
// RouteOption registers one or more OpenAPI Doc and middleware functions to the Route. // Optional
Options []RouteOption
// Middleware registers one or more middleware functions to the Route. // Optional
Middlewares []Middleware
}
type RouteOption ¶ added in v0.0.4
type RouteOption func(*Route)
RouteOption defines a function type that modifies a Route's documentation properties
func Deprecated ¶ added in v0.1.0
func Deprecated() RouteOption
Deprecated marks the route as deprecated
func Description ¶ added in v0.1.0
func Description(description string) RouteOption
Description adds a description to the route documentation.
func DocBasicAuth ¶ added in v0.0.18
func DocBasicAuth() RouteOption
DocBasicAuth marks the route as requiring Basic authentication
func DocBearerAuth ¶ added in v0.0.4
func DocBearerAuth() RouteOption
DocBearerAuth marks the route as requiring Bearer token authentication
func DocDeprecated ¶ added in v0.0.8
func DocDeprecated() RouteOption
DocDeprecated marks the route as deprecated
func DocDescription ¶ added in v0.0.13
func DocDescription(description string) RouteOption
DocDescription sets a description for the route
func DocErrorResponse ¶ added in v0.0.7
func DocErrorResponse(status int, v any) RouteOption
DocErrorResponse defines an error response schema for a specific HTTP status code in the route's OpenAPI documentation. Deprecated: This function is deprecated in favor of DocResponse(status, v).
Parameters:
- status: the HTTP status code (e.g., 400, 404, 500).
- v: a Go value (e.g., a struct instance) whose type will be used to generate the OpenAPI schema for the error response.
Returns:
- A RouteOption function that adds the error schema to the route's documentation.
func DocHeader ¶ added in v0.0.4
func DocHeader(name, typ, desc string, required bool) RouteOption
DocHeader adds a header parameter to the route documentation name: header name typ: header value type (e.g., "string", "int") desc: header description required: whether the header is required
func DocHeaderWithDefault ¶ added in v0.1.0
func DocHeaderWithDefault(name, typ, desc string, required bool, defvalue any) RouteOption
DocHeaderWithDefault adds a header parameter to the route documentation with default (if provided) name: header name typ: header value type (e.g., "string", "int") desc: header description required: whether the header is required defvalue: default value to use
func DocHide ¶ added in v0.0.19
func DocHide() RouteOption
DocHide marks the route to be excluded from OpenAPI documentation.
func DocOperationId ¶ added in v0.0.19
func DocOperationId(operationId string) RouteOption
func DocPathParam ¶ added in v0.0.4
func DocPathParam(name, typ, desc string) RouteOption
DocPathParam adds a path parameter to the route documentation name: parameter name typ: parameter type (e.g., "string", "int", "uuid") desc: parameter description
func DocPathParamWithDefault ¶ added in v0.1.1
func DocPathParamWithDefault(name, typ, desc string, defvalue any) RouteOption
DocPathParamWithDefault adds a path parameter to the route documentation name: parameter name typ: parameter type (e.g., "string", "int", "uuid") desc: parameter description defvalue: default value to use.
func DocQueryParam ¶ added in v0.0.4
func DocQueryParam(name, typ, desc string, required bool) RouteOption
DocQueryParam adds a query parameter to the route documentation name: parameter name typ: parameter type (e.g., "string", "int") desc: parameter description required: whether the parameter is required
func DocQueryParamWithDefault ¶ added in v0.1.0
func DocQueryParamWithDefault(name, typ, desc string, required bool, defvalue any) RouteOption
DocQueryParamWithDefault adds a query parameter to the route documentation (with default if provided) name: parameter name typ: parameter type (e.g., "string", "int") desc: parameter description required: whether the parameter is required defvalue: default value to use
func DocRequestBody ¶ added in v0.0.5
func DocRequestBody(v any) RouteOption
DocRequestBody defines the request body schema for the route v: a Go value whose type will be used to generate the request schema
func DocResponse ¶ added in v0.0.4
func DocResponse(statusOrValue any, vOptional ...any) RouteOption
DocResponse registers a response schema for the route's OpenAPI documentation. It can be used in two ways:
- DocResponse(status int, value any) - Defines a response schema for the specified HTTP status code (e.g., 200, 201, 400).
- DocResponse(value any) - Shorthand for DocResponse(200, value).
Examples:
DocResponse(201, CreatedResponse{}) // response for 201 Created
DocResponse(400, ErrorResponse{}) // response for 400 Bad request
DocResponse(response{}) // response: assumes status 200
func DocResponseHeader ¶ added in v0.0.13
func DocResponseHeader(name, typ string, desc ...string) RouteOption
DocResponseHeader adds a response header to the route documentation name: header name typ: header value type (e.g., "string", "int") desc: header description, optional
func DocSummary ¶ added in v0.0.4
func DocSummary(summary string) RouteOption
DocSummary sets a short summary description for the route
func DocTag ¶ added in v0.0.4
func DocTag(tag string) RouteOption
DocTag adds a single tag to categorize the route
func DocTags ¶ added in v0.0.4
func DocTags(tags ...string) RouteOption
DocTags adds multiple tags to categorize the route
func Hide ¶ added in v0.1.0
func Hide() RouteOption
Hide marks the route to be excluded from OpenAPI documentation.
func OperationId ¶ added in v0.1.0
func OperationId(operationId string) RouteOption
OperationId sets a unique identifier for the operation in the OpenAPI documentation.
func Request ¶ added in v0.1.0
func Request(v any) RouteOption
Request registers the request schema for a route. The provided value must be a struct or a pointer to a struct.
This schema is used for both OpenAPI documentation and request validation.
Field mapping rules:
- Request body: A field named `Body`, or a field tagged with `json:"body"`, is treated as the request body.
- Path parameters: Fields tagged with `path:"name"` or `param:"name"` are treated as path parameters.
- Query parameters: Fields tagged with `query:"name"` are treated as query parameters.
- Headers: Fields tagged with `header:"name"` are treated as HTTP headers.
- Cookies: Fields tagged with `cookie:"name"` are treated as HTTP cookies.
- Any remaining fields are treated as general request metadata or ignored if not applicable.
func Response ¶
func Response(v any) RouteOption
Response registers the response schema for a route. The provided value must be a struct or a pointer to a struct.
This schema is used for OpenAPI documentation and response representation.
Field mapping rules:
- Status code: A field named `Status` is interpreted as the HTTP status code (default: 200 if omitted).
- Response body: A field named `Body`, or a field tagged with `json:",inline"`, is treated as the response body.
- Headers: Fields tagged with `header:"name"` are treated as HTTP response headers.
- Cookies: Fields tagged with `cookie:"name"` are treated as HTTP cookies.
- Any remaining fields are treated as general response metadata or ignored if not applicable.
Example:
type CreateUserResponse struct {
Status int `json:"status"`
Body User `json:"body"`
Trace string `header:"X-Trace-ID"`
SessionId string `cookie:"session_id"`
}
func Summary ¶ added in v0.1.0
func Summary(summary string) RouteOption
Summary sets a short summary description for the route
func Tag ¶ added in v0.1.0
func Tag(tag string) RouteOption
Tag adds a single tag to categorize the route
func Tags ¶ added in v0.1.0
func Tags(tags ...string) RouteOption
Tags adds multiple tags to categorize the route
func UseMiddleware ¶ added in v0.0.15
func UseMiddleware(m ...Middleware) RouteOption
UseMiddleware registers one or more middleware functions to the Route.
func WithIO ¶ added in v0.1.0
func WithIO(req any, res any) RouteOption
WithIO registers both request and response schemas for a route in one call. It is a convenience helper that combines Request and Response.
type SchemaInfo ¶ added in v0.0.5
SchemaInfo holds additional information about a schema for better naming. It's used when generating OpenAPI schemas from Go types.
type SecurityRequirement ¶ added in v0.0.18
type SecurityScheme ¶ added in v0.0.18
type SecurityScheme struct {
Extensions map[string]any `json:"-" yaml:"-"`
Origin *Origin `json:"__origin__,omitempty" yaml:"__origin__,omitempty"`
Name string
// Type string // "http", "oauth2", "apiKey"
Type string
// Scheme string // "basic", "bearer", etc.
Scheme string
BearerFormat string
// In string // "header", "query", "cookie"
In string
Flows *OAuthFlows
Description string
}
type SecuritySchemes ¶ added in v0.0.18
type SecuritySchemes []SecurityScheme
func (SecuritySchemes) ToOpenAPI ¶ added in v0.0.18
func (ss SecuritySchemes) ToOpenAPI() openapi3.SecuritySchemes
type SendFunc ¶ added in v0.0.10
SendFunc defines the signature for a function that sends an SSE message.
type Serializer ¶ added in v0.2.1
Serializer defines how to convert data to string format
Implement this interface to create custom serializers for SSE messages.
type Server ¶ added in v0.0.5
type Server struct {
Extensions map[string]any `json:"-" yaml:"-"`
// Server URL (e.g., "https://api.example.com/v1")
URL string `json:"url" yaml:"url"`
// Optional server description
Description string `json:"description,omitempty" yaml:"description,omitempty"`
}
Server represents an API server location where the API is hosted
type Servers ¶ added in v0.0.5
type Servers []Server
Servers is a list of Server objects representing API server locations
type StreamOptions ¶ added in v0.2.1
type StreamOptions struct {
// Serializer to use for the stream messages
Serializer Serializer
// PingEnabled indicates whether to send periodic ping messages to keep the connection alive.
PingInterval time.Duration
// OnError is a callback function to handle errors during streaming.
OnError func(error)
}
type Template ¶ added in v0.3.2
type Template struct {
// contains filtered or unexported fields
}
func NewTemplate ¶ added in v0.3.2
NewTemplate creates a template from embedded filesystem
func NewTemplateFromDirectory ¶ added in v0.3.2
NewTemplateFromDirectory creates a template from a directory
Example:
tmpl, err := okapi.NewTemplateFromDirectory("templates", ".html", ".tmpl")
if err != nil {
// handle error
}
o := okapi.New().WithRenderer(tmpl)
func NewTemplateFromFiles ¶ added in v0.3.2
NewTemplateFromFiles creates a template from file system with pattern
Example:
tmpl, err := okapi.NewTemplateFromFiles("public/views/*.html")
if err != nil {
// handle error
}
o := okapi.New().WithRenderer(tmpl)
func NewTemplateWithConfig ¶ added in v0.3.2
func NewTemplateWithConfig(config TemplateConfig) (*Template, error)
NewTemplateWithConfig creates a template using configuration
Example: With configuration
tmpl, _ := NewTemplateWithConfig(TemplateConfig{
FS: os.DirFS("templates"),
Pattern: "**/*.html",
Funcs: template.FuncMap{"upper": strings.ToUpper},
})
if err != nil {
// handle error
}
o := okapi.New().WithRenderer(tmpl)
func (*Template) AddTemplate ¶ added in v0.3.2
AddTemplate allows adding templates dynamically after creation
Example:
err := tmpl.AddTemplate("newTemplate", "<h1>{{.Title}}</h1>")
if err != nil {
// handle error
}
func (*Template) AddTemplateFile ¶ added in v0.3.2
AddTemplateFile adds a template from a file
Example:
err := tmpl.AddTemplateFile("path/to/template.html")
if err != nil {
// handle error
}
type TemplateConfig ¶ added in v0.3.2
type TemplateConfig struct {
// File pattern (e.g., "views/*.html")
Pattern string
// Embedded or custom filesystem
FS fs.FS
// Custom template functions
Funcs template.FuncMap
// Base directory for templates
BaseDir string
}
TemplateConfig holds configuration for template loading
type TestServer ¶ added in v0.1.3
func NewTestServer ¶ added in v0.1.3
func NewTestServer(t TestingT) *TestServer
NewTestServer creates and starts a new Okapi test server.
Example:
testServer := okapi.NewTestServer(t)
testServer.Get("/books", GetBooksHandler)
okapitest.GET(t, testServer.BaseURL+"/books").ExpectStatusOK().ExpectBodyContains("The Go Programming Language")
func NewTestServerOn ¶ added in v0.1.3
func NewTestServerOn(t TestingT, port int) *TestServer
NewTestServerOn creates and starts a new Okapi test server.
Example:
testServer := okapi.NewTestServerOn(t,80801)
testServer.Get("/books", GetBooksHandler)
okapitest.GET(t, testServer.BaseURL+"/books").ExpectStatusOK().ExpectBodyContains("The Go Programming Language")
type TextSerializer ¶ added in v0.2.1
type TextSerializer struct{}
TextSerializer for plain text/string data
type ValidationError ¶ added in v0.0.5
type ValidationError struct {
Field string `json:"field"`
Message string `json:"message"`
Value any `json:"value,omitempty"`
}
ValidationError represents validation error details
type ValidationErrorResponse ¶ added in v0.0.5
type ValidationErrorResponse struct {
ErrorResponse
Errors []ValidationError `json:"errors"`
}
ValidationErrorResponse extends ErrorResponse for validation errors
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
cli
command
|
|
|
group
command
|
|
|
middleware
command
|
|
|
multipart
command
|
|
|
route-definition
command
|
|
|
sample
command
|
|
|
sse
command
|
|
|
template
command
|
|
|
tests
command
|
|
|
tls
command
|
|
|
validation-binding
command
|
|

