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.
Blazing Fast Routing: Optimized HTTP router with low overhead for high-performance applications.
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 ¶
- Constants
- Variables
- 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 ValidateAddr(addr string) bool
- type BasicAuth
- type BasicAuthMiddleware
- type BodyLimit
- type Contact
- type Context
- func (c *Context) Abort(err error) error
- func (c *Context) AbortBadGateway(msg ...string) error
- func (c *Context) AbortBadRequest(msg ...string) error
- func (c *Context) AbortConflict(msg ...string) error
- func (c *Context) AbortExpectationFailed(msg ...string) error
- func (c *Context) AbortFailedDependency(msg ...string) error
- func (c *Context) AbortForbidden(msg ...string) error
- func (c *Context) AbortGatewayTimeout(msg ...string) error
- func (c *Context) AbortGone(msg ...string) error
- func (c *Context) AbortHTTPVersionNotSupported(msg ...string) error
- func (c *Context) AbortInsufficientStorage(msg ...string) error
- func (c *Context) AbortInternalServerError(msg ...string) error
- func (c *Context) AbortLengthRequired(msg ...string) error
- func (c *Context) AbortLocked(msg ...string) error
- func (c *Context) AbortLoopDetected(msg ...string) error
- func (c *Context) AbortMethodNotAllowed(msg ...string) error
- func (c *Context) AbortMisdirectedRequest(msg ...string) error
- func (c *Context) AbortNetworkAuthenticationRequired(msg ...string) error
- func (c *Context) AbortNotAcceptable(msg ...string) error
- func (c *Context) AbortNotExtended(msg ...string) error
- func (c *Context) AbortNotFound(msg ...string) error
- func (c *Context) AbortNotImplemented(msg ...string) error
- func (c *Context) AbortPaymentRequired(msg ...string) error
- func (c *Context) AbortPreconditionFailed(msg ...string) error
- func (c *Context) AbortPreconditionRequired(msg ...string) error
- func (c *Context) AbortProxyAuthRequired(msg ...string) error
- func (c *Context) AbortRequestEntityTooLarge(msg ...string) error
- func (c *Context) AbortRequestHeaderFieldsTooLarge(msg ...string) error
- func (c *Context) AbortRequestTimeout(msg ...string) error
- func (c *Context) AbortRequestURITooLong(msg ...string) error
- func (c *Context) AbortRequestedRangeNotSatisfiable(msg ...string) error
- func (c *Context) AbortServiceUnavailable(msg ...string) error
- func (c *Context) AbortTeapot(msg ...string) error
- func (c *Context) AbortTooEarly(msg ...string) error
- func (c *Context) AbortTooManyRequests(msg ...string) error
- func (c *Context) AbortUnauthorized(msg ...string) error
- func (c *Context) AbortUnavailableForLegalReasons(msg ...string) error
- func (c *Context) AbortUnsupportedMediaType(msg ...string) error
- func (c *Context) AbortUpgradeRequired(msg ...string) error
- func (c *Context) AbortValidationError(msg ...string) error
- func (c *Context) AbortValidationErrors(errors []ValidationError, msg ...string) error
- func (c *Context) AbortVariantAlsoNegotiates(msg ...string) error
- func (c *Context) AbortWithError(code int, msg string, err error) error
- func (c *Context) AbortWithJSON(code int, jsonObj interface{}) 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) 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) 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) MaxMultipartMemory() int64
- func (c *Context) OK(v any) error
- func (c *Context) Param(key string) string
- func (c *Context) Query(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) 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) 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 DocBuilder
- func (b *DocBuilder) AsOption() RouteOption
- func (b *DocBuilder) BearerAuth() *DocBuilder
- func (b *DocBuilder) Build() RouteOption
- func (b *DocBuilder) Deprecated() *DocBuilder
- func (b *DocBuilder) ErrorResponse(status int, v any) *DocBuilder
- func (b *DocBuilder) Header(name, typ, desc string, required bool) *DocBuilder
- func (b *DocBuilder) PathParam(name, typ, desc string) *DocBuilder
- func (b *DocBuilder) QueryParam(name, typ, desc string, required bool) *DocBuilder
- func (b *DocBuilder) RequestBody(v any) *DocBuilder
- func (b *DocBuilder) Response(v any) *DocBuilder
- func (b *DocBuilder) Summary(summary string) *DocBuilder
- func (b *DocBuilder) Tags(tags ...string) *DocBuilder
- type ErrorResponse
- type Group
- func (g *Group) BasePath() string
- func (g *Group) Delete(path string, h HandleFunc, opts ...RouteOption) *Route
- func (g *Group) Disable() *Group
- func (g *Group) Enable() *Group
- func (g *Group) Get(path string, h HandleFunc, 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 HandleFunc, opts ...RouteOption) *Route
- func (g *Group) Okapi() *Okapi
- func (g *Group) Options(path string, h HandleFunc, opts ...RouteOption) *Route
- func (g *Group) Patch(path string, h HandleFunc, opts ...RouteOption) *Route
- func (g *Group) Post(path string, h HandleFunc, opts ...RouteOption) *Route
- func (g *Group) Put(path string, h HandleFunc, opts ...RouteOption) *Route
- func (g *Group) SetBasePath(basePath string)
- func (g *Group) SetDisabled(disabled bool) *Group
- func (g *Group) Trace(path string, h HandleFunc, opts ...RouteOption) *Route
- func (g *Group) Use(m ...Middleware)
- func (g *Group) UseMiddleware(mw func(http.Handler) http.Handler)
- type HandleFunc
- type JWTAuth
- type Jwk
- type Jwks
- type License
- type Logger
- type M
- type Message
- type Middleware
- type Okapi
- func (o *Okapi) Any(path string, h HandleFunc, opts ...RouteOption) *Route
- func (o *Okapi) Connect(path string, h HandleFunc, opts ...RouteOption) *Route
- func (o *Okapi) Delete(path string, h HandleFunc, opts ...RouteOption) *Route
- func (o *Okapi) DisableAccessLog() *Okapi
- func (o *Okapi) Get(path string, h HandleFunc, opts ...RouteOption) *Route
- func (o *Okapi) GetContext() *Context
- func (o *Okapi) Group(path string, middlewares ...Middleware) *Group
- func (o *Okapi) Handle(method, path string, h HandleFunc, 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 HandleFunc, opts ...RouteOption) *Route
- func (o *Okapi) Middlewares() []Middleware
- func (o *Okapi) Next(h HandleFunc) HandleFunc
- func (o *Okapi) Options(path string, h HandleFunc, opts ...RouteOption) *Route
- func (o *Okapi) Patch(path string, h HandleFunc, opts ...RouteOption) *Route
- func (o *Okapi) Post(path string, h HandleFunc, opts ...RouteOption) *Route
- func (o *Okapi) Put(path string, h HandleFunc, opts ...RouteOption) *Route
- 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) error
- func (o *Okapi) Start() 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()
- func (o *Okapi) Trace(path string, h HandleFunc, opts ...RouteOption) *Route
- func (o *Okapi) Use(middlewares ...Middleware)
- func (o *Okapi) UseMiddleware(mw func(http.Handler) http.Handler)
- func (o *Okapi) With(options ...OptionFunc) *Okapi
- func (o *Okapi) WithAddr(addr string) *Okapi
- func (o *Okapi) WithCORS(cors Cors) *Okapi
- func (o *Okapi) WithDebug() *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) WithOpenAPIDocs(cfg ...OpenAPI) *Okapi
- func (o *Okapi) WithPort(port int) *Okapi
- func (o *Okapi) WithReadTimeout(seconds int) *Okapi
- func (o *Okapi) WithStrictSlash(strict bool) *Okapi
- func (o *Okapi) WithWriteTimeout(seconds int) *Okapi
- type OpenAPI
- type OptionFunc
- func WithAccessLogDisabled() OptionFunc
- func WithAddr(addr string) OptionFunc
- func WithCors(cors Cors) OptionFunc
- func WithDebug() OptionFunc
- func WithIdleTimeout(t int) OptionFunc
- func WithLogger(logger *slog.Logger) OptionFunc
- func WithMaxMultipartMemory(max int64) OptionFunc
- func WithMux(mux *mux.Router) OptionFunc
- func WithOpenAPIDisabled() OptionFunc
- func WithPort(port int) OptionFunc
- func WithReadTimeout(t int) OptionFunc
- func WithServer(server *http.Server) 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 Param
- type Params
- type Renderer
- type RendererFunc
- type Response
- type Route
- type RouteOption
- func DocAutoPathParams() RouteOption
- func DocBearerAuth() RouteOption
- func DocDeprecated() RouteOption
- func DocErrorResponse(status int, v any) RouteOption
- func DocHeader(name, typ, desc string, required bool) RouteOption
- func DocPathParam(name, typ, desc string) RouteOption
- func DocQueryParam(name, typ, desc string, required bool) RouteOption
- func DocRequestBody(v any) RouteOption
- func DocResponse(v any) RouteOption
- func DocSummary(summary string) RouteOption
- func DocTag(tag string) RouteOption
- func DocTags(tags ...string) RouteOption
- type Router
- type SchemaInfo
- type Send
- type Server
- type Servers
- type Store
- type ValidateFunc
- type ValidationError
- type ValidationErrorResponse
- type Validator
Constants ¶
const ( ContentTypeHeader = "Content-Type" AcceptHeader = "Accept" LocationHeader = "Location" FrameworkName = "Okapi" TRUE = "true" OpenApiVersion = "3.0.0" OpenApiURL = "http://localhost:8080" OpenApiDocPrefix = "/docs" AccessControlAllowOrigin = "Access-Control-Allow-Origin" AccessControlAllowHeaders = "Access-Control-Allow-Headers" AccessControlExposeHeaders = "Access-Control-Expose-Headers" AccessControlAllowMethods = "Access-Control-Allow-Methods" AccessControlMaxAge = "Access-Control-Max-Age" AccessControlAllowCredentials = "Access-Control-Allow-Credentials" )
const ( StatusNotFound = http.StatusNotFound StatusBadRequest = http.StatusBadRequest StatusForbidden = http.StatusForbidden StatusInternalServerError = http.StatusInternalServerError )
Constants for HTTP Status Codes
const ( DELETE = http.MethodDelete GET = http.MethodGet HEAD = http.MethodHead OPTIONS = http.MethodOptions POST = http.MethodPost PUT = http.MethodPut PATCH = http.MethodPatch CONNECT = http.MethodConnect TRACE = http.MethodTrace )
HTTP methods
const ( JSON = "application/json" XML = "application/xml" HTML = "text/html" FORM = "application/x-www-form-urlencoded" FormData = "multipart/form-data" PLAIN = "text/plain" PLAINTEXT = "text/plain" CSV = "text/csv" JAVASCRIPT = "application/javascript" YAML = "application/yaml" YamlX = "application/x-yaml" YamlText = "text/yaml" PROTOBUF = "application/protobuf" FormURLEncoded = "application/x-www-form-urlencoded" )
Mime types
const ( Int = "int" Int64 = "int64" Float = "float" DateTime = "date-time" Date = "date" UUID = "uuid" Bool = "bool" String = "string" )
Variables ¶
var ( DefaultWriter io.Writer = os.Stdout DefaultErrorWriter io.Writer = os.Stderr DefaultPort = 8080 DefaultAddr = ":8080" )
var (
ErrNoRenderer = errors.New("no renderer set for context")
)
Functions ¶
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 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 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 HandleFunc) HandleFunc
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 HandleFunc) HandleFunc
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 HandleFunc) HandleFunc
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 Context ¶
type Context struct {
http.Handler
// Request is the http.Request object
Request *http.Request
// Response http.ResponseWriter
Response Response
// contains filtered or unexported fields
}
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) 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.
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 and stops execution.
func (*Context) AbortWithJSON ¶ added in v0.0.2
AbortWithJSON writes a custom JSON error response.
func (*Context) AbortWithStatus ¶ added in v0.0.2
AbortWithStatus writes an error response with status code and custom message.
func (*Context) AcceptLanguage ¶
AcceptLanguage returns the Accept-Language header values as a slice. Trims whitespace from each language tag.
func (*Context) Bind ¶
Bind binds the request data to the provided struct based on the content type and tags.
func (*Context) BindMultipart ¶
func (*Context) ContentType ¶
ContentType returns the Content-Type header value.
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) 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) MaxMultipartMemory ¶
MaxMultipartMemory returns the maximum memory for multipart form
func (*Context) Query ¶
Query retrieves a URL query parameter value. Returns empty string if parameter doesn't exist.
func (*Context) QueryMap ¶
QueryMap returns all query parameters as a map. Only includes the first value for each parameter.
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) SetMaxMultipartMemory ¶ added in v0.0.7
SetMaxMultipartMemory sets the maximum memory for multipart form (default: 32 MB)
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 HandleFunc) HandleFunc
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) 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.
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) 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) 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) 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(v any) *DocBuilder
Response adds a response schema to the route documentation using the provided value.
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 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"`
Path string `json:"path,omitempty"`
}
ErrorResponse represents a standardized error response structure
type Group ¶
type Group struct {
// contains filtered or unexported fields
}
func (*Group) BasePath ¶
BasePath returns the group's base path that prefixes all routes in this group.
func (*Group) Delete ¶
func (g *Group) Delete(path string, h HandleFunc, opts ...RouteOption) *Route
Delete registers a DELETE route within the group with the given path and handler.
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 HandleFunc, 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 HandleFunc, 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 HandleFunc, 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 HandleFunc, 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 HandleFunc, 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 HandleFunc, opts ...RouteOption) *Route
Put registers a PUT route within the group with the given path and handler.
func (*Group) SetBasePath ¶
SetBasePath updates the group's base path. Note: Use with caution as it affects all routes in the group.
func (*Group) SetDisabled ¶ added in v0.0.6
SetDisabled sets the disabled state of the Group. When disabled is true, all routes in the group return 404 Not Found. Returns the Group to allow method chaining.
func (*Group) Trace ¶
func (g *Group) Trace(path string, h HandleFunc, opts ...RouteOption) *Route
Trace registers a TRACE route within the group with the given path and handler.
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.
type HandleFunc ¶
HandleFunc is a function type that takes a Context and returns an error.
func LoggerMiddleware ¶
func LoggerMiddleware(next HandleFunc) HandleFunc
LoggerMiddleware is a middleware that logs request details like method, URL, client IP, status, duration, referer, and user agent.
type JWTAuth ¶
type JWTAuth struct {
SecretKey []byte
// Static JWKS (JSON Web Key Set) loaded from file or base64. Optional.
JwksFile *Jwks
// URL to a remote JWKS endpoint for public key discovery. Optional.
JwksUrl string
// Expected audience ("aud") claim in the token. Optional.
Audience string
// Issuer Expected issuer ("iss") claim in the token. Optional.
Issuer string
// RsaKey Public RSA key for verifying RS256 tokens. Optional.
RsaKey *rsa.PublicKey
// Algo Expected signing algorithm (e.g., "RS256", "HS256"). Optional.
Algo string
// TokenLookup Where to extract the token from (e.g., "header:Authorization", "query:token", "cookie:jwt").
TokenLookup string
// ContextKey where validated token claims will be stored (e.g., "user").
ContextKey string
}
JWTAuth is a configuration struct for JWT-based authentication middleware.
You must configure at least one token verification mechanism: - SecretKey: 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:
func (JWTAuth) Middleware ¶
func (jwtAuth JWTAuth) Middleware(next HandleFunc) HandleFunc
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 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 is the identifier for the SSE connection.
ID string `json:"id" xml:"id"`
// Data is the Data to be sent to the SSE connection.
Data any `json:"message"`
// Event is the event type for the SSE connection.
Event string `json:"event"`
}
Message is a struct that represents a Server-Sent Events (SSE) connection.
type Middleware ¶
type Middleware func(next HandleFunc) HandleFunc
type Okapi ¶
type Okapi struct {
Renderer Renderer
// 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 HandleFunc, opts ...RouteOption) *Route
Any registers a route that matches any HTTP method with the given path and handler function. Returns the created *Route
func (*Okapi) Connect ¶
func (o *Okapi) Connect(path string, h HandleFunc, opts ...RouteOption) *Route
Connect registers a new CONNECT route with the given path and handler function. Returns the created *Route
func (*Okapi) Delete ¶
func (o *Okapi) Delete(path string, h HandleFunc, opts ...RouteOption) *Route
Delete registers a new DELETE route with the given path and handler function. Returns the created *Route
func (*Okapi) DisableAccessLog ¶ added in v0.0.4
func (*Okapi) Get ¶
func (o *Okapi) Get(path string, h HandleFunc, opts ...RouteOption) *Route
Get registers a new GET route with the given path and handler function. Returns the created *Route
func (*Okapi) GetContext ¶
GetContext returns the current context
func (*Okapi) Group ¶
func (o *Okapi) Group(path 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 HandleFunc, 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 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 HandleFunc 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 HandleFunc, opts ...RouteOption) *Route
Head registers a new HEAD route with the given path and handler function. Returns the created *Route
func (*Okapi) Middlewares ¶
func (o *Okapi) Middlewares() []Middleware
Middlewares returns the list of middlewares
func (*Okapi) Next ¶
func (o *Okapi) Next(h HandleFunc) HandleFunc
Next applies the middlewares in correct order
func (*Okapi) Options ¶
func (o *Okapi) Options(path string, h HandleFunc, opts ...RouteOption) *Route
Options registers a new OPTIONS route with the given path and handler function. Returns the created *Route
func (*Okapi) Patch ¶
func (o *Okapi) Patch(path string, h HandleFunc, opts ...RouteOption) *Route
Patch registers a new PATCH route with the given path and handler function. Returns the created *Route
func (*Okapi) Post ¶
func (o *Okapi) Post(path string, h HandleFunc, 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.
func (*Okapi) Put ¶
func (o *Okapi) Put(path string, h HandleFunc, opts ...RouteOption) *Route
Put registers a new PUT route with the given path and handler function. Returns the created *Route
func (*Okapi) ServeHTTP ¶
func (o *Okapi) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements the http.Handler interface
func (*Okapi) SetContext ¶
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) Trace ¶
func (o *Okapi) Trace(path string, h HandleFunc, opts ...RouteOption) *Route
Trace registers a new TRACE route with the given path and handler function. Returns the created *Route
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 HandleFunc) HandleFunc
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 HandleFunc to allow smooth interop.
func (*Okapi) With ¶
func (o *Okapi) With(options ...OptionFunc) *Okapi
With applies the provided options to the Okapi instance
func (*Okapi) WithIdleTimeout ¶ added in v0.0.4
func (*Okapi) WithMaxMultipartMemory ¶ added in v0.0.7
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) WithReadTimeout ¶ added in v0.0.4
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
// PathPrefix is the URL prefix for accessing the documentation
PathPrefix string // e.g., "/docs" (default)
Servers Servers // List of server URLs where the API is hosted
Licence License // License information for the API
Contact Contact // Contact information for the API maintainers
}
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 WithCors ¶ added in v0.0.2
func WithCors(cors Cors) OptionFunc
WithCors returns an OptionFunc that configures CORS settings
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 WithMux ¶
func WithMux(mux *mux.Router) OptionFunc
WithMux sets the router for the Okapi instance
func WithOpenAPIDisabled ¶ added in v0.0.5
func WithOpenAPIDisabled() OptionFunc
WithOpenAPIDisabled disabled OpenAPI Docs
func WithReadTimeout ¶ added in v0.0.3
func WithReadTimeout(t int) OptionFunc
WithReadTimeout returns an OptionFunc that sets the read timeout
func WithServer ¶
func WithServer(server *http.Server) OptionFunc
WithServer sets the HTTP server for the Okapi instance
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 RendererFunc ¶
type Response ¶
type Response interface {
http.ResponseWriter
BodyBytesSent() int
Status() int
Close()
Hijack() (net.Conn, *bufio.ReadWriter, error)
}
Response interface defines the methods for writing HTTP responses.
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) 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) SetDisabled ¶ added in v0.0.6
SetDisabled sets the disabled state of the Route. When disabled is true, the route returns 404 Not Found. Returns the Route to allow method chaining.
type RouteOption ¶ added in v0.0.4
type RouteOption func(*Route)
RouteOption defines a function type that modifies a Route's documentation properties
func DocAutoPathParams ¶ added in v0.0.4
func DocAutoPathParams() RouteOption
DocAutoPathParams automatically extracts path parameters from the route path and adds them to the documentation. It skips parameters that are already defined.
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 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.
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 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 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 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(v any) RouteOption
DocResponse defines the response schema for the route v: a Go value whose type will be used to generate the response schema
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
type SchemaInfo ¶ added in v0.0.5
type SchemaInfo struct {
Schema *openapi3.SchemaRef // Reference to the OpenAPI schema
TypeName string // The original Go type name
Package string // The package name (optional)
}
SchemaInfo holds additional information about a schema for better naming. It's used when generating OpenAPI schemas from Go types.
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 Store ¶ added in v0.0.9
type Store struct {
// contains filtered or unexported fields
}
func NewStoreData ¶ added in v0.0.9
func NewStoreData() *Store
NewStoreData creates a new instance of Store
type ValidateFunc ¶
ValidateFunc is a function type that implements the Validator interface
func (ValidateFunc) Validate ¶
func (vf ValidateFunc) Validate(data any) error
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
