okapi

package module
v0.0.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 5, 2025 License: MIT Imports: 36 Imported by: 11

README

OKAPI - Lightweight Go Web Framework with OpenAPI 3.0 & Swagger UI

Tests Go Report Card Go Go Reference GitHub Release

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.

Okapi logo


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 DocumentationOpenAPI 3.0 & Swagger UI integrated out of the box—auto-generate API docs with minimal effort.

✔ Dynamic Route Management – Easily enable or disable individual routes or groups, with automatic Swagger sync and no code commenting.

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
  • Easy testing

Built for speed, simplicity, and real-world use—whether you're prototyping or running in production.


Why Choose Okapi?
  • Easy to Learn – Familiar Go syntax and intuitive APIs mean you’re productive in minutes.
  • Highly Flexible – Designed to adapt to your architecture and workflow—not the other way around.
  • Built for Production – Lightweight, fast, and reliable under real-world load.

Ideal for:

  • High-performance REST APIs
  • Composable microservices
  • Rapid prototyping
  • Learning & teaching Go web development

Whether you're building your next startup, internal tools, or side projects—Okapi scales with you.


Installation

mkdir myapi && cd myapi
go mod init myapi
go get github.com/jkaninda/okapi

Quick Start

Create a file named main.go:

package main

import (
	"net/http"
	"github.com/jkaninda/okapi"
)

func main() {
	o := okapi.Default()

	o.Get("/", func(c okapi.Context) error {
		return c.OK(okapi.M{"message": "Welcome to Okapi!"})
	},
		okapi.DocSummary("Welcome page"),
	)

	if err := o.Start(); err != nil {
		panic(err)
	}
}

Run your server:

go run .

Visit http://localhost:8080 to see the response:

{"message": "Welcome to Okapi!"}

Visit http://localhost:8080/docs/ to se the documentation


Routing

Okapi supports all standard HTTP methods:

o.Get("/books", getBooks)
o.Post("/books", createBook)
o.Get("/books/:id", getBook)
o.Put("/books/:id", updateBook)
o.Delete("/books/:id", deleteBook)
Route Groups

Organize routes with nesting and middleware:

api := o.Group("/api")

v1 := api.Group("/v1")
v2 := api.Group("/v2")

v1.Get("/users", getUsers)
v2.Get("/users", getUsers)


admin := api.Group("/admin", adminMiddleware)
admin.Get("/dashboard", getDashboard)

Request Handling

Path Parameters
o.Get("/books/:id", func(c okapi.Context) error {
	id := c.Param("id")
	return c.String(http.StatusOK, id)
})
Query Parameters
o.Get("/books", func(c okapi.Context) error {
	name := c.Query("name")
	return c.String(http.StatusOK, name)
})

Handling Form Data

Multipart Form (multipart/form-data)

Handle standard form fields and file uploads:

o.Post("/books", func(c okapi.Context) error {
	name := c.FormValue("name")
	price := c.FormValue("price")

	logo, err := c.FormFile("logo")
	if err != nil {
		return c.AbortWithError(http.StatusBadRequest, err)
	}
	file, err := logo.Open()
	if err != nil {
		return c.AbortWithError(http.StatusBadRequest, err)
	}
	defer file.Close()
	// You can now read or save the uploaded file
	return c.String(http.StatusOK, "File uploaded successfully")
})

Struct Binding

Bind request data directly into a struct from multiple sources:

type Book struct {
	ID    int    `json:"id" param:"id" query:"id" form:"id"`
	Name  string `json:"name" xml:"name" form:"name" min:"4" max:"50" required:"true"`
	Price int    `json:"price" form:"price" required:"true"`
	Logo *multipart.FileHeader `form:"logo" required:"true"`
    Content string `header:"Content-Type" json:"content-type" xml:"content-type" required:"true"`
	// Supports both ?tags=a&tags=b and ?tags=a,b
	Tags []string `form:"tags" query:"tags" default:"a,b"`
}

o.Post("/books", func(c okapi.Context) error {
	book := &Book{}
	if err := c.Bind(book); err != nil {
		return c.ErrorBadRequest(err)
	}
	return c.JSON(http.StatusOK, book)
})
Supported Sources
  • Path parameters: param
  • Query parameters: query
  • Form fields: form
  • JSON body: json
  • XML body: xml
  • Headers: header

Validation and Defaults

Okapi supports simple, declarative validation using struct tags.

Semantics
Field Type Tag Meaning
string min:"10" Minimum length = 10
string max:"50" Maximum length = 50
number min:"5" Minimum value = 5
number max:"100" Maximum value = 100
any default:"..." Default value if empty
any required:"true" Field must be provided

Middleware

Built-in Example (Basic Auth)
auth := okapi.BasicAuthMiddleware{
	Username: "admin",
	Password: "password",
	Realm:    "Restricted",
}

o.Use(auth.Middleware)
o.Get("/admin", adminHandler)
CORS middleware
cors := okapi.Cors{AllowedOrigins: []string{"http://localhost:8080", "https://example.com"}, AllowedHeaders: []string{}}
o := okapi.New(okapi.WithCors(cors))
	o.Get("/", func(c okapi.Context) error {
		return c.String(http.StatusOK, "Hello World!")
	})
Custom Middleware
func logger(next okapi.HandlerFunc) okapi.HandlerFunc {
	return func(c okapi.Context) error {
		start := time.Now()
		err := next(c)
		log.Printf("Request took %v", time.Since(start))
		return err
	}
}

o.Use(logger)

OpenAPI/Swagger Integration

Okapi provides automatic OpenAPI (Swagger) documentation generation with built-in UI support. The documentation is dynamically generated from your route definitions, keeping your API documentation always in sync with your implementation.

Quick Start

To enable OpenAPI docs with default settings:

o := okapi.Default()  // Docs available at /docs
Custom Configuration

Configure OpenAPI settings during initialization:

	o := okapi.New().WithOpenAPIDocs(
        okapi.OpenAPI{
        PathPrefix: "/swagger",  // Base path for documentation
        Title:     "Bookstore API",  // Displayed in UI
        Version:   "1.0.0",         // API version
        Contact: okapi.Contact{
        Name:  "API Support",
        Email: "support@bookstore.com",
		},
		},
)
Documenting Routes

Okapi provides two ways to attach OpenAPI documentation to your routes:

1. Composable Functions (Direct Style)

This approach uses individual okapi.Doc* functions for each aspect of your route documentation. It’s concise and works well for simple routes.

o.Get("/books", getBooksHandler,
  okapi.DocSummary("List all available books"),
  okapi.DocTags("Books"),
  okapi.DocQueryParam("author", "string", "Filter by author name", false),
  okapi.DocQueryParam("limit", "int", "Maximum results to return (default 20)", false),
  okapi.DocResponse([]Book{}),
)
2. Fluent Builder Style (okapi.Doc() + .Build()

For more complex or dynamic documentation setup, Okapi offers a fluent builder API. Use okapi.Doc() to begin building, chain options, and call .Build() or .AsOption() to finalize.

o.Post("/books", createBookHandler,
    okapi.Doc().
    Summary("Add a new book to inventory").
    Tags("Books").
    BearerAuth().
    RequestBody(BookRequest{}).
    Response(Book{}).
    Build(),
)
Available Documentation Options
Method Description
DocSummary() Short endpoint description
DocTag()/DocTags() Groups related endpoints
DocBearerAuth() Enables Bearer token authentication
DocRequestBody() Documents request body structure
DocResponse() Documents response structure
DocPathParam() Documents path parameters
DocQueryParam() Documents query parameters
DocHeader() Documents header parameters
Swagger UI Preview

Okapi automatically generates Swagger UI for all documented routes:

Okapi Swagger Interface


Enabling and Disabling Routes & Groups

Okapi gives you flexible control over your API by allowing routes and route groups to be dynamically enabled or disabled. This is a clean and efficient alternative to commenting out code when you want to temporarily remove endpoints.

Overview

You can disable:

  • Individual routes — blocks access to a specific endpoint
  • Route groups — disables an entire section of your API, including all nested routes

This behavior is reflected both in runtime responses and API documentation.

Type HTTP Response Swagger Docs Affects Child Routes
Disabled Route 404 Not Found Hidden N/A
Disabled Group 404 Not Found Hidden Yes — all nested
Key Features
  • Disabled routes/groups return a 404 Not Found
  • Automatically excluded from Swagger/OpenAPI documentation
  • Disabling a group recursively disables all nested routes and sub-groups
  • No need to comment out code — just call .Disable() or .Enable()
Use Cases
  • Temporarily removing endpoints during maintenance
  • Controlling access based on feature flags
  • Deprecating old API versions
  • Creating toggleable test or staging routes
Usage Example
app := okapi.Default()

// Create the root API group
api := app.Group("api")

// Define and disable v1 group
v1 := api.Group("v1").Disable() // All v1 routes return 404 and are hidden from docs
v1.Get("/", func(c okapi.Context) error {
    return c.OK(okapi.M{"version": "v1"})
})

// Define active v2 group
v2 := api.Group("v2")
v2.Get("/", func(c okapi.Context) error {
    return c.OK(okapi.M{"version": "v2"})
})

// Start the server
if err := app.Start(); err != nil {
    panic(err)
}
Behavior Details
  • Disabled Route:

    • Responds with 404 Not Found
    • Excluded from Swagger docs
  • Disabled Group:

    • All nested routes and sub-groups are recursively disabled
    • All affected routes are hidden from Swagger

To re-enable any route or group, simply call the .Enable() method or remove the .Disable() call.


Templating

Using a Custom Renderer
o.Renderer = okapi.RendererFunc(func(w io.Writer, name string, data interface{}, c okapi.Context) error {
	tmpl, err := template.ParseFiles("templates/" + name + ".html")
	if err != nil {
		return err
	}
	return tmpl.ExecuteTemplate(w, name, data)
})
Or Using a Struct-Based Renderer
type Template struct {
	templates *template.Template
}

func (t *Template) Render(w io.Writer, name string, data interface{}, c okapi.Context) error {
	return t.templates.ExecuteTemplate(w, name, data)
}

tmpl := &Template{
	templates: template.Must(template.ParseGlob("templates/*.html")),
}

o.Renderer = tmpl
Rendering a View
o.Get("/", func(c okapi.Context) error {
	return c.Render(http.StatusOK, "welcome", okapi.M{
		"title":   "Welcome Page",
		"message": "Hello from Okapi!",
	})
})

Static File Serving

Serve static assets and individual files:

// Serve a single file
o.Get("/favicon.ico", func(c okapi.Context) error {
	c.ServeFile("public/favicon.ico")
	return nil
})

// Serve an entire directory
o.Static("/static", "public/assets")

TLS Server

// Initialize TLS configuration for secure HTTPS connections
    tls, err := okapi.LoadTLSConfig("path/to/cert.pem", "path/to/key.pem", "", false)
    if err != nil {
    panic(fmt.Sprintf("Failed to load TLS configuration: %v", err))
    }
    // Create a new Okapi instance with default config
    // With OpenAPI enabled, /docs
    o := okapi.Default()
    // Use HTTPS
    // o := okapi.New(okapi.WithTLS(tls))
    
    // Configure a secondary HTTPS server listening on port 8443
    // This creates both HTTP (8080) and HTTPS (8443) endpoints
    o.With(okapi.WithTLSServer(":8443", tls))
    
    // Register application routes and handlers
    o.Get("/", func(c okapi.Context) error {
    return c.JSON(http.StatusOK, okapi.M{
    "message": "Welcome to Okapi!",
    "status":  "operational",
    })
    })
    // Start the servers
    // This will launch both HTTP and HTTPS listeners in separate goroutines
    log.Println("Starting server on :8080 (HTTP) and :8443 (HTTPS)")
    if err := o.Start(); err != nil {
    panic(fmt.Sprintf("Server failed to start: %v", err))
    }
    }

Contributing

Contributions are welcome!

  1. Fork the repository
  2. Create a feature branch
  3. Commit your changes
  4. Push to your fork
  5. Open a Pull Request

Give a Star! ⭐

⭐ If you find Okapi useful, please consider giving it a star on GitHub!

License

This project is licensed under the MIT License. See the LICENSE file for details.

Copyright (c) 2025 Jonas Kaninda

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

View Source
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"
)
View Source
const (
	StatusNotFound            = http.StatusNotFound
	StatusBadRequest          = http.StatusBadRequest
	StatusUnauthorized        = http.StatusUnauthorized
	StatusForbidden           = http.StatusForbidden
	StatusInternalServerError = http.StatusInternalServerError
)

Constants for HTTP Status Codes

View Source
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

View Source
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

View Source
const (
	Int      = "int"
	Int64    = "int64"
	Float    = "float"
	DateTime = "date-time"
	Date     = "date"
	UUID     = "uuid"
	Bool     = "bool"
	String   = "string"
)

Variables

View Source
var (
	DefaultWriter      io.Writer = os.Stdout
	DefaultErrorWriter io.Writer = os.Stderr
	DefaultPort                  = 8080
	DefaultAddr                  = ":8080"
)
View Source
var (
	ErrNoRenderer = errors.New("no renderer set for context")
)

Functions

func GenerateJwtToken

func GenerateJwtToken(secret []byte, claims jwt.MapClaims, ttl time.Duration) (string, error)

GenerateJwtToken generates a JWT with custom claims and expiry

func IsClientError added in v0.0.5

func IsClientError(code int) bool

IsClientError checks if the status code is a 4xx client error.

func IsError added in v0.0.5

func IsError(code int) bool

IsError checks if the status code represents an error (4xx or 5xx).

func IsServerError added in v0.0.5

func IsServerError(code int) bool

IsServerError checks if the status code is a 5xx server error.

func LoadTLSConfig added in v0.0.3

func LoadTLSConfig(certFile, keyFile, caFile string, clientAuth bool) (*tls.Config, error)

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 RealIP

func RealIP(r *http.Request) string

RealIP extracts the real IP address of the client from the HTTP Request.

func ValidateAddr

func ValidateAddr(addr string) bool

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

type BasicAuthMiddleware struct {
	Username string
	Password string
	Realm    string
}

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 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

func (Contact) ToOpenAPI added in v0.0.5

func (c Contact) ToOpenAPI() *openapi3.Contact

ToOpenAPI converts Contact to openapi3.Contact. It transforms the custom Contact type to the format expected by the openapi3 package.

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

func (c *Context) Abort(err error) error

Abort writes a standardized 500 Internal Server Error response.

func (*Context) AbortBadGateway added in v0.0.5

func (c *Context) AbortBadGateway(msg ...string) error

AbortBadGateway writes a standardized 502 Bad Gateway response.

func (*Context) AbortBadRequest added in v0.0.2

func (c *Context) AbortBadRequest(msg ...string) error

AbortBadRequest writes a standardized 400 Bad Request response.

func (*Context) AbortConflict added in v0.0.2

func (c *Context) AbortConflict(msg ...string) error

AbortConflict writes a standardized 409 Conflict response.

func (*Context) AbortExpectationFailed added in v0.0.5

func (c *Context) AbortExpectationFailed(msg ...string) error

AbortExpectationFailed writes a standardized 417 Expectation Failed response.

func (*Context) AbortFailedDependency added in v0.0.5

func (c *Context) AbortFailedDependency(msg ...string) error

AbortFailedDependency writes a standardized 424 Failed Dependency response.

func (*Context) AbortForbidden added in v0.0.2

func (c *Context) AbortForbidden(msg ...string) error

AbortForbidden writes a standardized 403 Forbidden response.

func (*Context) AbortGatewayTimeout added in v0.0.5

func (c *Context) AbortGatewayTimeout(msg ...string) error

AbortGatewayTimeout writes a standardized 504 Gateway Timeout response.

func (*Context) AbortGone added in v0.0.5

func (c *Context) AbortGone(msg ...string) error

AbortGone writes a standardized 410 Gone response.

func (*Context) AbortHTTPVersionNotSupported added in v0.0.5

func (c *Context) AbortHTTPVersionNotSupported(msg ...string) error

AbortHTTPVersionNotSupported writes a standardized 505 HTTP Version Not Supported response.

func (*Context) AbortInsufficientStorage added in v0.0.5

func (c *Context) AbortInsufficientStorage(msg ...string) error

AbortInsufficientStorage writes a standardized 507 Insufficient Storage response.

func (*Context) AbortInternalServerError added in v0.0.5

func (c *Context) AbortInternalServerError(msg ...string) error

AbortInternalServerError writes a standardized 500 Internal Server Error response.

func (*Context) AbortLengthRequired added in v0.0.5

func (c *Context) AbortLengthRequired(msg ...string) error

AbortLengthRequired writes a standardized 411 Length Required response.

func (*Context) AbortLocked added in v0.0.5

func (c *Context) AbortLocked(msg ...string) error

AbortLocked writes a standardized 423 Locked response.

func (*Context) AbortLoopDetected added in v0.0.5

func (c *Context) AbortLoopDetected(msg ...string) error

AbortLoopDetected writes a standardized 508 Loop Detected response.

func (*Context) AbortMethodNotAllowed added in v0.0.5

func (c *Context) AbortMethodNotAllowed(msg ...string) error

AbortMethodNotAllowed writes a standardized 405 Method Not Allowed response.

func (*Context) AbortMisdirectedRequest added in v0.0.5

func (c *Context) AbortMisdirectedRequest(msg ...string) error

AbortMisdirectedRequest writes a standardized 421 Misdirected Request response.

func (*Context) AbortNetworkAuthenticationRequired added in v0.0.5

func (c *Context) AbortNetworkAuthenticationRequired(msg ...string) error

AbortNetworkAuthenticationRequired writes a standardized 511 Network Authentication Required response.

func (*Context) AbortNotAcceptable added in v0.0.5

func (c *Context) AbortNotAcceptable(msg ...string) error

AbortNotAcceptable writes a standardized 406 Not Acceptable response.

func (*Context) AbortNotExtended added in v0.0.5

func (c *Context) AbortNotExtended(msg ...string) error

AbortNotExtended writes a standardized 510 Not Extended response.

func (*Context) AbortNotFound added in v0.0.2

func (c *Context) AbortNotFound(msg ...string) error

AbortNotFound writes a standardized 404 Not Found response.

func (*Context) AbortNotImplemented added in v0.0.5

func (c *Context) AbortNotImplemented(msg ...string) error

AbortNotImplemented writes a standardized 501 Not Implemented response.

func (*Context) AbortPaymentRequired added in v0.0.5

func (c *Context) AbortPaymentRequired(msg ...string) error

AbortPaymentRequired writes a standardized 402 Payment Required response.

func (*Context) AbortPreconditionFailed added in v0.0.5

func (c *Context) AbortPreconditionFailed(msg ...string) error

AbortPreconditionFailed writes a standardized 412 Precondition Failed response.

func (*Context) AbortPreconditionRequired added in v0.0.5

func (c *Context) AbortPreconditionRequired(msg ...string) error

AbortPreconditionRequired writes a standardized 428 Precondition Required response.

func (*Context) AbortProxyAuthRequired added in v0.0.5

func (c *Context) AbortProxyAuthRequired(msg ...string) error

AbortProxyAuthRequired writes a standardized 407 Proxy Authentication Required response.

func (*Context) AbortRequestEntityTooLarge added in v0.0.5

func (c *Context) AbortRequestEntityTooLarge(msg ...string) error

AbortRequestEntityTooLarge writes a standardized 413 Request Entity Too Large response.

func (*Context) AbortRequestHeaderFieldsTooLarge added in v0.0.5

func (c *Context) AbortRequestHeaderFieldsTooLarge(msg ...string) error

AbortRequestHeaderFieldsTooLarge writes a standardized 431 Request Header Fields Too Large response.

func (*Context) AbortRequestTimeout added in v0.0.5

func (c *Context) AbortRequestTimeout(msg ...string) error

AbortRequestTimeout writes a standardized 408 Request Timeout response.

func (*Context) AbortRequestURITooLong added in v0.0.5

func (c *Context) AbortRequestURITooLong(msg ...string) error

AbortRequestURITooLong writes a standardized 414 Request-URI Too Long response.

func (*Context) AbortRequestedRangeNotSatisfiable added in v0.0.5

func (c *Context) AbortRequestedRangeNotSatisfiable(msg ...string) error

AbortRequestedRangeNotSatisfiable writes a standardized 416 Requested Range Not Satisfiable response.

func (*Context) AbortServiceUnavailable added in v0.0.5

func (c *Context) AbortServiceUnavailable(msg ...string) error

AbortServiceUnavailable writes a standardized 503 Service Unavailable response.

func (*Context) AbortTeapot added in v0.0.5

func (c *Context) AbortTeapot(msg ...string) error

AbortTeapot writes a standardized 418 I'm a teapot response.

func (*Context) AbortTooEarly added in v0.0.5

func (c *Context) AbortTooEarly(msg ...string) error

AbortTooEarly writes a standardized 425 Too Early response.

func (*Context) AbortTooManyRequests added in v0.0.2

func (c *Context) AbortTooManyRequests(msg ...string) error

AbortTooManyRequests writes a standardized 429 Too Many Requests response.

func (*Context) AbortUnauthorized added in v0.0.2

func (c *Context) AbortUnauthorized(msg ...string) error

AbortUnauthorized writes a standardized 401 Unauthorized response.

func (*Context) AbortUnavailableForLegalReasons added in v0.0.5

func (c *Context) AbortUnavailableForLegalReasons(msg ...string) error

AbortUnavailableForLegalReasons writes a standardized 451 Unavailable For Legal Reasons response.

func (*Context) AbortUnsupportedMediaType added in v0.0.5

func (c *Context) AbortUnsupportedMediaType(msg ...string) error

AbortUnsupportedMediaType writes a standardized 415 Unsupported Media Type response.

func (*Context) AbortUpgradeRequired added in v0.0.5

func (c *Context) AbortUpgradeRequired(msg ...string) error

AbortUpgradeRequired writes a standardized 426 Upgrade Required response.

func (*Context) AbortValidationError added in v0.0.2

func (c *Context) AbortValidationError(msg ...string) error

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

func (c *Context) AbortVariantAlsoNegotiates(msg ...string) error

AbortVariantAlsoNegotiates writes a standardized 506 Variant Also Negotiates response.

func (*Context) AbortWithError

func (c *Context) AbortWithError(code int, msg string, err error) error

AbortWithError writes a standardized error response and stops execution.

func (*Context) AbortWithJSON added in v0.0.2

func (c *Context) AbortWithJSON(code int, jsonObj interface{}) error

AbortWithJSON writes a custom JSON error response.

func (*Context) AbortWithStatus added in v0.0.2

func (c *Context) AbortWithStatus(code int, message string) error

AbortWithStatus writes an error response with status code and custom message.

func (*Context) Accept

func (c *Context) Accept() []string

Accept returns the Accept header values as a slice.

func (*Context) AcceptLanguage

func (c *Context) AcceptLanguage() []string

AcceptLanguage returns the Accept-Language header values as a slice. Trims whitespace from each language tag.

func (*Context) B

func (c *Context) B(v any) error

B is a shortcut for Bind, allowing you to bind request data to a struct.

func (*Context) Bind

func (c *Context) Bind(out any) error

Bind binds the request data to the provided struct based on the content type and tags.

func (*Context) BindForm

func (c *Context) BindForm(v any) error

func (*Context) BindJSON

func (c *Context) BindJSON(v any) error

func (*Context) BindMultipart

func (c *Context) BindMultipart(out any) error

func (*Context) BindProtoBuf

func (c *Context) BindProtoBuf(v proto.Message) error

func (*Context) BindQuery

func (c *Context) BindQuery(v any) error

func (*Context) BindXML

func (c *Context) BindXML(v any) error

func (*Context) BindYAML

func (c *Context) BindYAML(v any) error

func (*Context) ContentType

func (c *Context) ContentType() string

ContentType returns the Content-Type header value.

func (*Context) Cookie

func (c *Context) Cookie(name string) (string, error)

Cookie retrieves a cookie value by name. Returns empty string and error if cookie not found.

func (*Context) Copy

func (c *Context) Copy() *Context

Copy creates a shallow copy of the context with a new data map. Maintains thread safety during the copy operation.

func (*Context) Data

func (c *Context) Data(code int, contentType string, data []byte) error

Data writes a raw byte response with the given content type and status code.

func (*Context) Error

func (c *Context) Error(code int, message string) error

Error writes a basic error response with the given status code and message.

func (*Context) ErrorBadGateway added in v0.0.5

func (c *Context) ErrorBadGateway(message any) error

ErrorBadGateway writes a 502 Bad Gateway response.

func (*Context) ErrorBadRequest added in v0.0.2

func (c *Context) ErrorBadRequest(message any) error

ErrorBadRequest writes a 400 Bad Request response.

func (*Context) ErrorConflict added in v0.0.2

func (c *Context) ErrorConflict(message any) error

ErrorConflict writes a 409 Conflict response.

func (*Context) ErrorExpectationFailed added in v0.0.5

func (c *Context) ErrorExpectationFailed(message any) error

ErrorExpectationFailed writes a 417 Expectation Failed response.

func (*Context) ErrorFailedDependency added in v0.0.5

func (c *Context) ErrorFailedDependency(message any) error

ErrorFailedDependency writes a 424 Failed Dependency response.

func (*Context) ErrorForbidden added in v0.0.2

func (c *Context) ErrorForbidden(message any) error

ErrorForbidden writes a 403 Forbidden response.

func (*Context) ErrorGatewayTimeout added in v0.0.5

func (c *Context) ErrorGatewayTimeout(message any) error

ErrorGatewayTimeout writes a 504 Gateway Timeout response.

func (*Context) ErrorGone added in v0.0.5

func (c *Context) ErrorGone(message any) error

ErrorGone writes a 410 Gone response.

func (*Context) ErrorHTTPVersionNotSupported added in v0.0.5

func (c *Context) ErrorHTTPVersionNotSupported(message any) error

ErrorHTTPVersionNotSupported writes a 505 HTTP Version Not Supported response.

func (*Context) ErrorInsufficientStorage added in v0.0.5

func (c *Context) ErrorInsufficientStorage(message any) error

ErrorInsufficientStorage writes a 507 Insufficient Storage response.

func (*Context) ErrorInternalServerError added in v0.0.2

func (c *Context) ErrorInternalServerError(message any) error

ErrorInternalServerError writes a 500 Internal Server Error response.

func (*Context) ErrorLengthRequired added in v0.0.5

func (c *Context) ErrorLengthRequired(message any) error

ErrorLengthRequired writes a 411 Length Required response.

func (*Context) ErrorLocked added in v0.0.5

func (c *Context) ErrorLocked(message any) error

ErrorLocked writes a 423 Locked response.

func (*Context) ErrorLoopDetected added in v0.0.5

func (c *Context) ErrorLoopDetected(message any) error

ErrorLoopDetected writes a 508 Loop Detected response.

func (*Context) ErrorMethodNotAllowed added in v0.0.5

func (c *Context) ErrorMethodNotAllowed(message any) error

ErrorMethodNotAllowed writes a 405 Method Not Allowed response.

func (*Context) ErrorMisdirectedRequest added in v0.0.5

func (c *Context) ErrorMisdirectedRequest(message any) error

ErrorMisdirectedRequest writes a 421 Misdirected Request response.

func (*Context) ErrorNetworkAuthenticationRequired added in v0.0.5

func (c *Context) ErrorNetworkAuthenticationRequired(message any) error

ErrorNetworkAuthenticationRequired writes a 511 Network Authentication Required response.

func (*Context) ErrorNotAcceptable added in v0.0.5

func (c *Context) ErrorNotAcceptable(message any) error

ErrorNotAcceptable writes a 406 Not Acceptable response.

func (*Context) ErrorNotExtended added in v0.0.5

func (c *Context) ErrorNotExtended(message any) error

ErrorNotExtended writes a 510 Not Extended response.

func (*Context) ErrorNotFound added in v0.0.2

func (c *Context) ErrorNotFound(message any) error

ErrorNotFound writes a 404 Not Found response.

func (*Context) ErrorNotImplemented added in v0.0.5

func (c *Context) ErrorNotImplemented(message any) error

ErrorNotImplemented writes a 501 Not Implemented response.

func (*Context) ErrorPaymentRequired added in v0.0.5

func (c *Context) ErrorPaymentRequired(message any) error

ErrorPaymentRequired writes a 402 Payment Required response.

func (*Context) ErrorPreconditionFailed added in v0.0.5

func (c *Context) ErrorPreconditionFailed(message any) error

ErrorPreconditionFailed writes a 412 Precondition Failed response.

func (*Context) ErrorPreconditionRequired added in v0.0.5

func (c *Context) ErrorPreconditionRequired(message any) error

ErrorPreconditionRequired writes a 428 Precondition Required response.

func (*Context) ErrorProxyAuthRequired added in v0.0.5

func (c *Context) ErrorProxyAuthRequired(message any) error

ErrorProxyAuthRequired writes a 407 Proxy Authentication Required response.

func (*Context) ErrorRequestEntityTooLarge added in v0.0.5

func (c *Context) ErrorRequestEntityTooLarge(message any) error

ErrorRequestEntityTooLarge writes a 413 Request Entity Too Large response.

func (*Context) ErrorRequestHeaderFieldsTooLarge added in v0.0.5

func (c *Context) ErrorRequestHeaderFieldsTooLarge(message any) error

ErrorRequestHeaderFieldsTooLarge writes a 431 Request Header Fields Too Large response.

func (*Context) ErrorRequestTimeout added in v0.0.5

func (c *Context) ErrorRequestTimeout(message any) error

ErrorRequestTimeout writes a 408 Request Timeout response.

func (*Context) ErrorRequestURITooLong added in v0.0.5

func (c *Context) ErrorRequestURITooLong(message any) error

ErrorRequestURITooLong writes a 414 Request-URI Too Long response.

func (*Context) ErrorRequestedRangeNotSatisfiable added in v0.0.5

func (c *Context) ErrorRequestedRangeNotSatisfiable(message any) error

ErrorRequestedRangeNotSatisfiable writes a 416 Requested Range Not Satisfiable response.

func (*Context) ErrorServiceUnavailable added in v0.0.2

func (c *Context) ErrorServiceUnavailable(message any) error

ErrorServiceUnavailable writes a 503 Service Unavailable response.

func (*Context) ErrorTeapot added in v0.0.5

func (c *Context) ErrorTeapot(message any) error

ErrorTeapot writes a 418 I'm a teapot response (RFC 2324).

func (*Context) ErrorTooEarly added in v0.0.5

func (c *Context) ErrorTooEarly(message any) error

ErrorTooEarly writes a 425 Too Early response.

func (*Context) ErrorTooManyRequests added in v0.0.2

func (c *Context) ErrorTooManyRequests(message any) error

ErrorTooManyRequests writes a 429 Too Many Requests response.

func (*Context) ErrorUnauthorized added in v0.0.2

func (c *Context) ErrorUnauthorized(message any) error

ErrorUnauthorized writes a 401 Unauthorized response.

func (*Context) ErrorUnavailableForLegalReasons added in v0.0.5

func (c *Context) ErrorUnavailableForLegalReasons(message any) error

ErrorUnavailableForLegalReasons writes a 451 Unavailable For Legal Reasons response.

func (*Context) ErrorUnprocessableEntity added in v0.0.2

func (c *Context) ErrorUnprocessableEntity(message any) error

ErrorUnprocessableEntity writes a 422 Unprocessable Entity response.

func (*Context) ErrorUnsupportedMediaType added in v0.0.5

func (c *Context) ErrorUnsupportedMediaType(message any) error

ErrorUnsupportedMediaType writes a 415 Unsupported Media Type response.

func (*Context) ErrorUpgradeRequired added in v0.0.5

func (c *Context) ErrorUpgradeRequired(message any) error

ErrorUpgradeRequired writes a 426 Upgrade Required response.

func (*Context) ErrorVariantAlsoNegotiates added in v0.0.5

func (c *Context) ErrorVariantAlsoNegotiates(message any) error

ErrorVariantAlsoNegotiates writes a 506 Variant Also Negotiates response.

func (*Context) Form

func (c *Context) Form(key string) string

Form retrieves a form value after parsing the form data.

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) FormValue

func (c *Context) FormValue(key string) string

FormValue retrieves a form value, including multipart form data.

func (*Context) Get

func (c *Context) Get(key string) (any, bool)

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

func (c *Context) GetBool(key string) bool

GetBool retrieves a boolean value from the context. Returns false if key doesn't exist or value isn't a bool.

func (*Context) GetInt

func (c *Context) GetInt(key string) int

GetInt retrieves an integer value from the context. Returns 0 if key doesn't exist or value isn't an int.

func (*Context) GetInt64

func (c *Context) GetInt64(key string) int64

GetInt64 retrieves an int64 value from the context. Returns 0 if key doesn't exist or value isn't an int64.

func (*Context) GetString

func (c *Context) GetString(key string) string

GetString retrieves a string value from the context. Returns empty string if key doesn't exist or value isn't a string.

func (*Context) GetTime

func (c *Context) GetTime(key string) (time.Time, bool)

GetTime retrieves a time.Time value from the context's data store.

func (*Context) HTML

func (c *Context) HTML(code int, file string, data any) error

HTML renders an HTML template from a file with the given status code.

func (*Context) HTMLView

func (c *Context) HTMLView(code int, templateStr string, data any) error

HTMLView renders an HTML template from a string with the given status code.

func (*Context) Header

func (c *Context) Header(key string) string

Header gets a request header by key.

func (*Context) Headers

func (c *Context) Headers() map[string][]string

Headers returns all request headers as a map.

func (*Context) IsSSE

func (c *Context) IsSSE() bool

IsSSE checks if the request is for Server-Sent Events (SSE).

func (*Context) IsWebSocketUpgrade

func (c *Context) IsWebSocketUpgrade() bool

IsWebSocketUpgrade checks if the request is a WebSocket upgrade request.

func (*Context) JSON

func (c *Context) JSON(code int, v any) error

JSON writes a JSON response with the given status code.

func (*Context) OK added in v0.0.5

func (c *Context) OK(v any) error

OK writes a JSON response with 200 status code.

func (*Context) Param

func (c *Context) Param(key string) string

Param retrieves a URL path parameter value.

func (*Context) Query

func (c *Context) Query(key string) string

Query retrieves a URL query parameter value. Returns empty string if parameter doesn't exist.

func (*Context) QueryMap

func (c *Context) QueryMap() map[string]string

QueryMap returns all query parameters as a map. Only includes the first value for each parameter.

func (*Context) RealIP

func (c *Context) RealIP() string

RealIP returns the client's real IP address, handling proxies.

func (*Context) Redirect

func (c *Context) Redirect(code int, location string)

Redirect sends a redirect response to the specified location.

func (*Context) Referer

func (c *Context) Referer() string

Referer retrieves the Referer header value from the request.

func (*Context) Render

func (c *Context) Render(code int, name string, data interface{}) error

Render renders a template using the configured Renderer.

func (*Context) ServeFile

func (c *Context) ServeFile(path string)

ServeFile serves a file from the filesystem.

func (*Context) ServeFileAttachment

func (c *Context) ServeFileAttachment(path, filename string)

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

func (c *Context) ServeFileInline(path, filename string)

ServeFileInline serves a file to be displayed inline in the browser.

func (*Context) Set

func (c *Context) Set(key string, value any)

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) SetHeader

func (c *Context) SetHeader(key, value string)

SetHeader sets a response header.

func (*Context) ShouldBind

func (c *Context) ShouldBind(v any) (bool, error)

func (*Context) String

func (c *Context) String(code int, data any) error

String is an alias for Text for convenience.

func (*Context) Text

func (c *Context) Text(code int, v any) error

Text writes a plain text response with the given status code.

func (*Context) WriteStatus

func (c *Context) WriteStatus(code int)

WriteStatus writes the HTTP status code to the response.

func (*Context) XML

func (c *Context) XML(code int, v any) error

XML writes an XML response with the given status code.

func (*Context) YAML

func (c *Context) YAML(code int, data any) error

YAML writes a YAML response with the given status code.

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) 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

func (g *Group) BasePath() string

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

func (g *Group) Disable() *Group

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

func (g *Group) Enable() *Group

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) 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) Okapi

func (g *Group) Okapi() *Okapi

Okapi returns the parent Okapi instance associated with this group.

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

func (g *Group) SetBasePath(basePath string)

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

func (g *Group) SetDisabled(disabled bool) *Group

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.

type HandleFunc

type HandleFunc func(c Context) error

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

func (JWTAuth) ValidateToken

func (j JWTAuth) ValidateToken(c Context) (jwt.MapClaims, error)

ValidateToken checks the JWT token and returns the claims if valid

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.

func (License) ToOpenAPI added in v0.0.5

func (l License) ToOpenAPI() *openapi3.License

ToOpenAPI converts License to openapi3.License. It transforms the custom License type to the format expected by the openapi3 package.

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 M

type M map[string]any

M is shortcut of map[string]any

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.

func (*Message) Close

func (s *Message) Close(w http.ResponseWriter) error

Close closes the SSE connection by flushing the response writer.

func (*Message) Send

func (s *Message) Send(w http.ResponseWriter, data any, eventType string) (string, error)

Send sends a message to the 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 Default

func Default() *Okapi

Default creates a new Okapi instance with default settings.

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 (o *Okapi) DisableAccessLog() *Okapi

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

func (o *Okapi) GetContext() *Context

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:

  1. Normalizes the route path
  2. Creates a new Route instance
  3. Applies all registered middlewares to the handler
  4. Registers the route with the underlying router
  5. 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) Routes

func (o *Okapi) Routes() []Route

func (*Okapi) ServeHTTP

func (o *Okapi) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements the http.Handler interface

func (*Okapi) SetContext

func (o *Okapi) SetContext(ctx *Context)

func (*Okapi) Shutdown

func (o *Okapi) Shutdown(server *http.Server) error

Shutdown wraps graceful server shutdown with context

func (*Okapi) Start

func (o *Okapi) Start() error

Start starts the Okapi server

func (*Okapi) StartServer

func (o *Okapi) StartServer(server *http.Server) error

StartServer starts the Okapi server with the specified HTTP server

func (*Okapi) Static

func (o *Okapi) Static(prefix string, dir string)

Static serves static files under a path prefix, without directory listing

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

func (o *Okapi) StaticFile(path string, filepath string)

StaticFile serves a single file at the specified path.

func (*Okapi) Stop

func (o *Okapi) Stop()

Stop gracefully shuts down the Okapi server(s)

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) WithAddr added in v0.0.4

func (o *Okapi) WithAddr(addr string) *Okapi

func (*Okapi) WithCORS added in v0.0.4

func (o *Okapi) WithCORS(cors Cors) *Okapi

func (*Okapi) WithDebug added in v0.0.4

func (o *Okapi) WithDebug() *Okapi

func (*Okapi) WithIdleTimeout added in v0.0.4

func (o *Okapi) WithIdleTimeout(seconds int) *Okapi

func (*Okapi) WithLogger added in v0.0.4

func (o *Okapi) WithLogger(logger *slog.Logger) *Okapi

func (*Okapi) WithOpenAPIDocs added in v0.0.4

func (o *Okapi) WithOpenAPIDocs(cfg ...OpenAPI) *Okapi

WithOpenAPIDocs registers the OpenAPI JSON and Swagger UI handlers at the configured PathPrefix (default: /docs).

UI Path: /docs JSON Path: /openapi.json

func (*Okapi) WithPort added in v0.0.4

func (o *Okapi) WithPort(port int) *Okapi

func (*Okapi) WithReadTimeout added in v0.0.4

func (o *Okapi) WithReadTimeout(seconds int) *Okapi

func (*Okapi) WithStrictSlash added in v0.0.4

func (o *Okapi) WithStrictSlash(strict bool) *Okapi

func (*Okapi) WithWriteTimeout added in v0.0.4

func (o *Okapi) WithWriteTimeout(seconds int) *Okapi

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

func (o OpenAPI) ToOpenAPISpec() *openapi3.T

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 WithAddr

func WithAddr(addr string) OptionFunc

WithAddr sets the server address

func WithCors added in v0.0.2

func WithCors(cors Cors) OptionFunc

WithCors returns an OptionFunc that configures CORS settings

func WithDebug

func WithDebug() OptionFunc

WithDebug enables debug mode and access logging

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 WithOpenAPIDisabled added in v0.0.5

func WithOpenAPIDisabled() OptionFunc

WithOpenAPIDisabled disabled OpenAPI Docs

func WithPort

func WithPort(port int) OptionFunc

WithPort sets the server port

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 Param

type Param struct {
	Param struct {
		Key   string
		Value string
	}
}

type Params

type Params []Param

func (*Params) Get

func (p *Params) Get(key string) (string, bool)

type Renderer

type Renderer interface {
	Render(io.Writer, string, interface{}, Context) error
}

type RendererFunc

type RendererFunc func(io.Writer, string, interface{}, Context) error

func (RendererFunc) Render

func (f RendererFunc) Render(w io.Writer, name string, data interface{}, c Context) error

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
	RequestExample  map[string]interface{}
	ResponseExample map[string]interface{}
	Responses       map[int]any
	Description     string
	// contains filtered or unexported fields
}

func (*Route) Disable added in v0.0.6

func (r *Route) Disable() *Route

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

func (r *Route) Enable() *Route

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

func (r *Route) SetDisabled(disabled bool) *Route

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 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 schema for the route in the API documentation. This is an alias for RequestBody

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 Router

type Router struct {
	// contains filtered or unexported fields
}

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 Send

type Send func(data any, eventType string) (string, error)

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

func (Servers) ToOpenAPI added in v0.0.5

func (s Servers) ToOpenAPI() openapi3.Servers

ToOpenAPI converts Servers to openapi3.Servers. It transforms the custom Servers type to the format expected by the openapi3 package.

type ValidateFunc

type ValidateFunc func(data any) error

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

type Validator

type Validator interface {
	// Validate validates the data and returns an error if validation fails
	Validate(data any) error
}

Directories

Path Synopsis
examples
group command
middleware command
multipart command
sample command
sse command
template command
tls command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL