Documentation
¶
Overview ¶
Package okapi is a modern, minimalist HTTP web framework for Go, inspired by the simplicity of FastAPI.
Designed to be intuitive, lightweight, and powerful, Okapi makes it easy to build fast and flexible web applications and REST APIs.
Features:
- Clean and expressive API design
- Powerful binding from JSON, XML, forms, query, headers, and path parameters
- Route grouping and middleware chaining
- Built-in middleware: Basic Auth, JWT, OAuth
- Easy custom middleware support
- Cross-Origin Resource Sharing (CORS)
- Templating engine integration
- Static file serving
- Built entirely on Go’s standard library
- Simple and clear documentation
Index ¶
- Constants
- Variables
- func GenerateJwtToken(secret []byte, claims jwt.MapClaims, ttl time.Duration) (string, error)
- func LoadTLSConfig(certFile, keyFile, caFile string, clientAuth bool) (*tls.Config, error)
- func RealIP(r *http.Request) string
- func ValidateAddr(addr string) bool
- type BasicAuthMiddleware
- type BodyLimit
- type Context
- func (c *Context) Abort(err error) error
- func (c *Context) AbortBadRequest(msg ...string) error
- func (c *Context) AbortConflict(msg ...string) error
- func (c *Context) AbortForbidden(msg ...string) error
- func (c *Context) AbortNotFound(msg ...string) error
- func (c *Context) AbortTooManyRequests(msg ...string) error
- func (c *Context) AbortUnauthorized(msg ...string) error
- func (c *Context) AbortValidationError(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) Data(code int, contentType string, data []byte) error
- func (c *Context) Error(code int, message string) error
- func (c *Context) ErrorBadRequest(message string) error
- func (c *Context) ErrorConflict(message string) error
- func (c *Context) ErrorForbidden(message string) error
- func (c *Context) ErrorInternalServerError(message string) error
- func (c *Context) ErrorNotFound(message string) error
- func (c *Context) ErrorServiceUnavailable(message string) error
- func (c *Context) ErrorTooManyRequests(message string) error
- func (c *Context) ErrorUnauthorized(message string) error
- func (c *Context) ErrorUnprocessableEntity(message string) 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) 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) 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 ErrorResponse
- type Group
- func (g *Group) BasePath() string
- func (g *Group) Delete(path string, h HandleFunc, opts ...RouteOption) *Route
- func (g *Group) Get(path string, h HandleFunc, opts ...RouteOption) *Route
- func (g *Group) Group(path string, middlewares ...Middleware) *Group
- 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) Trace(path string, h HandleFunc, opts ...RouteOption) *Route
- func (g *Group) Use(m ...Middleware)
- type HandleFunc
- type JWTAuth
- 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 http.Handler, opts ...RouteOption)
- func (o *Okapi) HandleFunc(method, path string, h HandleFunc, opts ...RouteOption)
- 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) 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) 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 WithMux(mux *mux.Router) 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 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 DocRequest(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 Send
- type ValidateFunc
- 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 ( ErrNotFound = errors.New("not found") ErrFailedToParseMultiPart = errors.New("failed to parse multipart data") ErrInvalidMultiPartData = errors.New("invalid multipart data") )
Constants for Error Handling
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 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 BasicAuthMiddleware ¶
BasicAuthMiddleware provides basic authentication for routes.
func (*BasicAuthMiddleware) Middleware ¶
func (b *BasicAuthMiddleware) Middleware(next HandleFunc) HandleFunc
Middleware is a basic authentication middleware that checks the request's Basic Auth credentials.
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 Context ¶
type Context struct {
http.Handler
// Request is the http.Request object
Request *http.Request
// Response http.ResponseWriter
Response Response
// CtxData is a key/value store for storing data in the context
CtxData map[string]any
MaxMultipartMemory int64 // Maximum memory for multipart forms
// contains filtered or unexported fields
}
func (*Context) Abort ¶ added in v0.0.2
Abort writes an error response with 500 status code and standardized format.
func (*Context) AbortBadRequest ¶ added in v0.0.2
AbortBadRequest writes an error response with 400 status code and standardized format.
func (*Context) AbortConflict ¶ added in v0.0.2
AbortConflict writes an error response with 409 status code.
func (*Context) AbortForbidden ¶ added in v0.0.2
AbortForbidden writes an error response with 403 status code.
func (*Context) AbortNotFound ¶ added in v0.0.2
AbortNotFound writes an error response with 404 status code.
func (*Context) AbortTooManyRequests ¶ added in v0.0.2
AbortTooManyRequests writes an error response with 429 status code.
func (*Context) AbortUnauthorized ¶ added in v0.0.2
AbortUnauthorized writes an error response with 401 status code.
func (*Context) AbortValidationError ¶ added in v0.0.2
AbortValidationError writes an error response with 422 status code.
func (*Context) AbortWithError ¶
AbortWithError writes an error response with the given status code and standardized format. Returns the error for chaining.
func (*Context) AbortWithJSON ¶ added in v0.0.2
AbortWithJSON writes a custom JSON error response with the given status code.
func (*Context) AbortWithStatus ¶ added in v0.0.2
AbortWithStatus writes an error response with the given status code and message. Useful when you don't have an error object but just a 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) Copy ¶
Copy creates a shallow copy of the context with a new data map. Maintains thread safety during the copy operation.
func (*Context) Error ¶
Error writes an error response with the given status code and message. Returns an error if writing the response fails.
func (*Context) ErrorBadRequest ¶ added in v0.0.2
ErrorBadRequest writes a 400 Bad Request response. Returns an error if writing the response fails.
func (*Context) ErrorConflict ¶ added in v0.0.2
ErrorConflict writes a 409 Conflict response.
func (*Context) ErrorForbidden ¶ added in v0.0.2
ErrorForbidden writes a 403 Forbidden response.
func (*Context) ErrorInternalServerError ¶ added in v0.0.2
ErrorInternalServerError writes a 500 Internal Server Error response. Returns an error if writing the response fails.
func (*Context) ErrorNotFound ¶ added in v0.0.2
ErrorNotFound writes a 404 Not Found response. Returns an error if writing the response fails.
func (*Context) ErrorServiceUnavailable ¶ added in v0.0.2
ErrorServiceUnavailable writes a 503 Service Unavailable 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) ErrorUnprocessableEntity ¶ added in v0.0.2
ErrorUnprocessableEntity writes a 422 Unprocessable Entity 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) 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) 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 ErrorResponse ¶ added in v0.0.2
type ErrorResponse struct {
Code int `json:"code" xml:"code"`
Message string `json:"message" xml:"message"`
Details string `json:"details,omitempty" xml:"details,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) 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) 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) 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.
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
TokenLookup string // e.g., "header:Authorization", "query:token", "cookie:jwt"
ContextKey string // where to store claims in context, e.g. "user"
}
JWTAuth holds the config for JWT verification middleware.
func (JWTAuth) Middleware ¶
func (j JWTAuth) Middleware(next HandleFunc) HandleFunc
Middleware validates JWT tokens from the configured source
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 {
Server *http.Server
TLSServer *http.Server
Renderer Renderer
// contains filtered or unexported fields
}
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 http.Handler, opts ...RouteOption)
Handle registers a new route with the specified HTTP method, path, and http.Handler. It wraps the standard http.Handler into a HandleFunc signature and processes it similarly to HandleFunc.
Parameters:
- method: HTTP method (GET, POST, PUT, etc.)
- path: URL path pattern (supports path parameters)
- h: Standard http.Handler that processes the request
Middleware Processing:
All middlewares registered via Use() will be applied in order before the handler. The middleware chain is built using the Next() method.
Differences from HandleFunc:
- Accepts standard http.Handler instead of HandleFunc
- Handler errors must be handled by the http.Handler itself
- Returns nil error by default since http.Handler doesn't return errors
Example:
okapi.Handle("GET", "/static", http.FileServer(http.Dir("./public")))
func (*Okapi) HandleFunc ¶
func (o *Okapi) HandleFunc(method, path string, h HandleFunc, opts ...RouteOption)
HandleFunc registers a new route with the specified HTTP method, path, and handler function. It performs the following operations:
- Normalizes the route path
- Creates a new Route instance
- Applies all registered middlewares to the handler
- Registers the route with the underlying router
- Sets up error handling for the handler
Parameters:
- method: HTTP method (GET, POST, PUT, etc.)
- path: URL path pattern (supports path parameters)
- h: Handler function that processes the request
Middleware Processing:
All middlewares registered via Use() will be applied in order before the handler. The middleware chain is built using the Next() method.
Error Handling:
Any error returned by the handler will be converted to a 500 Internal Server Error.
Example:
okapi.HandleFunc("GET", "/users/:id", func(c Context) error {
id := c.Param("id")
// ... handler logic
return nil
})
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) 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) 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: /docs/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 openapi3.Servers // List of server URLs where the API is hosted
}
OpenAPI contains configuration for generating OpenAPI/Swagger documentation
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 WithMux ¶
func WithMux(mux *mux.Router) OptionFunc
WithMux sets the router for the Okapi instance
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
Handle HandleFunc
GroupPath string
Tags []string
Summary string
Request *openapi3.SchemaRef
Response *openapi3.SchemaRef
PathParams []*openapi3.ParameterRef
QueryParams []*openapi3.ParameterRef
Headers []*openapi3.ParameterRef
RequiresAuth bool
// contains filtered or unexported fields
}
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 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 DocRequest ¶ added in v0.0.4
func DocRequest(v any) RouteOption
DocRequest 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 ValidateFunc ¶
ValidateFunc is a function type that implements the Validator interface
func (ValidateFunc) Validate ¶
func (vf ValidateFunc) Validate(data any) error
