kono

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Feb 12, 2026 License: Apache-2.0 Imports: 31 Imported by: 0

README

Kono API Gateway

A lightweight, modular, and high-performance API Gateway for modern microservices.

Kono Gateway provides advanced routing, request fan-out, response aggregation, pluggable middleware, and extensibility through custom '.so' plugins.

It is built with simplicity, performance, and developer-friendly configuration in mind.

Documentation

Index

Constants

View Source
const (
	ErrorCodeRateLimitExceeded   = "RATE_LIMIT_EXCEEDED"
	ErrorCodePayloadTooLarge     = "PAYLOAD_TOO_LARGE"
	ErrorCodeUpstreamUnavailable = "UPSTREAM_UNAVAILABLE"
	ErrorCodeUpstreamError       = "UPSTREAM_ERROR"
	ErrorCodeUpstreamMalformed   = "UPSTREAM_MALFORMED"
	ErrorCodeInternal            = "INTERNAL"
)
View Source
const (
	PluginTypeRequest = iota
	PluginTypeResponse
)

Variables

This section is empty.

Functions

func WriteError

func WriteError(w http.ResponseWriter, code, message, requestID string, status int)

Types

type AggregatedResponse

type AggregatedResponse struct {
	Data    json.RawMessage
	Errors  []JSONError
	Partial bool
}

type AggregationConfig

type AggregationConfig struct {
	Strategy            string `json:"strategy" yaml:"strategy" toml:"strategy" validate:"required,oneof=array merge"`
	AllowPartialResults bool   `json:"allow_partial_results" yaml:"allow_partial_results" toml:"allow_partial_results"`
}

type CircuitBreakerConfig

type CircuitBreakerConfig struct {
	Enabled      bool          `json:"enabled" yaml:"enabled" toml:"enabled"`
	MaxFailures  int           `json:"max_failures" yaml:"max_failures" toml:"max_failures"`
	ResetTimeout time.Duration `json:"reset_timeout" yaml:"reset_timeout" toml:"reset_timeout"`
}

type CircuitBreakerPolicy

type CircuitBreakerPolicy struct {
	Enabled      bool
	MaxFailures  int
	ResetTimeout time.Duration
}

CircuitBreakerPolicy configures a per-upstream circuit breaker, including maximum consecutive failures, and the reset timeout after which the breaker will allow attempts again.

type Config

type Config struct {
	ConfigVersion string             `json:"config_version" yaml:"config_version" toml:"config_version" validate:"required,oneof=v1"`
	Name          string             `json:"name" yaml:"name" toml:"name" validate:"required"`
	Version       string             `json:"version" yaml:"version" toml:"version" validate:"required"`
	Debug         bool               `json:"debug" yaml:"debug" toml:"debug"`
	Server        ServerConfig       `json:"server" yaml:"server" toml:"server"`
	Dashboard     DashboardConfig    `json:"dashboard" yaml:"dashboard" toml:"dashboard"`
	Features      []FeatureConfig    `json:"features" yaml:"features" toml:"features"`
	Middlewares   []MiddlewareConfig `json:"middlewares" yaml:"middlewares" toml:"middlewares"`
	Routes        []RouteConfig      `json:"routes" yaml:"routes" toml:"routes" validate:"min=1,dive"`
}

func LoadConfig

func LoadConfig(path string) (Config, error)

type Context

type Context interface {
	Request() *http.Request
	Response() *http.Response

	SetRequest(req *http.Request)
	SetResponse(resp *http.Response)
}

Context is the internal interface that holds the request and response objects.

type DashboardConfig

type DashboardConfig struct {
	Enabled bool          `json:"enabled" yaml:"enabled" toml:"enabled"`
	Port    int           `json:"port" yaml:"port" toml:"port"`
	Timeout time.Duration `json:"timeout" yaml:"timeout" toml:"timeout"`
}

type FeatureConfig

type FeatureConfig struct {
	Enabled bool                   `json:"enabled" yaml:"enabled" toml:"enabled"`
	Name    string                 `json:"name" yaml:"name" toml:"name"`
	Config  map[string]interface{} `json:"config" yaml:"config" toml:"config"`
}

type JSONError

type JSONError struct {
	Code      string `json:"code"`
	Message   string `json:"message"`
	RequestID string `json:"request_id,omitempty"`
}

type JSONResponse

type JSONResponse struct {
	Data   json.RawMessage `json:"data,omitempty"`
	Errors []JSONError     `json:"errors,omitempty"`
}

JSONResponse is an output structure that wraps the final response from the gateway to the client.

type MetricsConfig

type MetricsConfig struct {
	Enabled  bool   `json:"enabled" yaml:"enabled" toml:"enabled"`
	Provider string `json:"provider" yaml:"provider" toml:"provider"`

	VictoriaMetrics VictoriaMetricsConfig `json:"victoria_metrics" yaml:"victoria_metrics" toml:"victoria_metrics"`
}

type Middleware

type Middleware interface {
	Name() string
	Init(cfg map[string]interface{}) error
	Handler(next http.Handler) http.Handler
}

type MiddlewareConfig

type MiddlewareConfig struct {
	Name          string                 `json:"name" yaml:"name" toml:"name"`
	Path          string                 `json:"path,omitempty" yaml:"path,omitempty" toml:"path,omitempty"`
	Config        map[string]interface{} `json:"config" yaml:"config" toml:"config"`
	CanFailOnLoad bool                   `json:"can_fail_on_load" yaml:"can_fail_on_load" toml:"can_fail_on_load"`
	Override      bool                   `json:"override" yaml:"override" toml:"override"`
}

type Plugin

type Plugin interface {
	Info() PluginInfo
	Init(cfg map[string]interface{})
	Type() PluginType
	Execute(ctx Context) error
}

Plugin is an interface that describes the implementation of plugins for modifying the request or response. Any custom plugin must implement this interface.

type PluginConfig

type PluginConfig struct {
	Name   string                 `json:"name" yaml:"name" toml:"name"`
	Path   string                 `json:"path,omitempty" yaml:"path,omitempty" toml:"path,omitempty"`
	Config map[string]interface{} `json:"config" yaml:"config" toml:"config"`
}

type PluginInfo

type PluginInfo struct {
	Name        string
	Description string
	Version     string
	Author      string
}

type PluginType

type PluginType int

type Policy

type Policy struct {
	AllowedStatuses     []int
	RequireBody         bool
	MapStatusCodes      map[int]int
	MaxResponseBodySize int64

	RetryPolicy    RetryPolicy
	CircuitBreaker CircuitBreakerPolicy
}

Policy defines the per-upstream configuration for handling HTTP responses, retries, and fault tolerance. Each upstream can have its own Policy instance.

type PolicyConfig

type PolicyConfig struct {
	AllowedStatuses     []int       `json:"allowed_status_codes" yaml:"allowed_status_codes" toml:"allowed_status_codes"`
	RequireBody         bool        `json:"allow_empty_body" yaml:"allow_empty_body" toml:"allow_empty_body"`
	MapStatusCodes      map[int]int `json:"map_status_codes" yaml:"map_status_codes" toml:"map_status_codes"`
	MaxResponseBodySize int64       `json:"max_response_body_size" yaml:"max_response_body_size" toml:"max_response_body_size"`

	RetryConfig          RetryConfig          `json:"retry" yaml:"retry" toml:"retry"`
	CircuitBreakerConfig CircuitBreakerConfig `json:"circuit_breaker" yaml:"circuit_breaker" toml:"circuit_breaker"`
}

type RetryConfig

type RetryConfig struct {
	MaxRetries      int           `json:"max_retries" yaml:"max_retries" toml:"max_retries"`
	RetryOnStatuses []int         `json:"retry_on_statuses" yaml:"retry_on_statuses" toml:"retry_on_statuses"`
	BackoffDelay    time.Duration `json:"backoff_delay" yaml:"backoff_delay" toml:"backoff_delay"`
}

type RetryPolicy

type RetryPolicy struct {
	MaxRetries      int
	RetryOnStatuses []int
	BackoffDelay    time.Duration
}

RetryPolicy specifies retry behavior for an upstream, including max retries, which statuses trigger retries, and backoff delay between attempts.

type Route

type Route struct {
	Path                 string
	Method               string
	Upstreams            []Upstream
	Aggregation          AggregationConfig
	MaxParallelUpstreams int64
	Plugins              []Plugin
	Middlewares          []Middleware
}

type RouteConfig

type RouteConfig struct {
	Path                 string             `json:"path" yaml:"path" toml:"path" validate:"required"`
	Method               string             `json:"method" yaml:"method" toml:"method" validate:"required"`
	Plugins              []PluginConfig     `json:"plugins" yaml:"plugins" toml:"plugins"`
	Middlewares          []MiddlewareConfig `json:"middlewares" yaml:"middlewares" toml:"middlewares"`
	Upstreams            []UpstreamConfig   `json:"upstreams" yaml:"upstreams" toml:"upstreams" validate:"required,min=1,dive"`
	Aggregation          AggregationConfig  `json:"aggregation" yaml:"aggregation" toml:"aggregation"`
	MaxParallelUpstreams int64              `json:"max_parallel_upstreams" yaml:"max_parallel_upstreams" toml:"max_parallel_upstreams"`
}

type Router

type Router struct {
	Routes []Route
	// contains filtered or unexported fields
}

func NewRouter

func NewRouter(routerConfigSet RouterConfigSet, log *zap.Logger) *Router

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP handles incoming HTTP requests through the full router pipeline.

The processing steps are:

1. Rate limiting (if enabled) – rejects requests exceeding allowed limits. 2. Route matching – finds a Route that matches the request method and path.

  • If no route is found, responds with 404.

3. Middleware execution – wraps the route handler with all configured middlewares in reverse order. 4. Request-phase plugins – executed before upstream dispatch. Can modify the request context. 5. Upstream dispatch – sends the request to all configured upstreams via the dispatcher.

  • If the dispatch fails (e.g., body too large), responds with an appropriate error. 6. Response aggregation – combines multiple upstream responses according to the route's aggregation strategy ("merge" or "array") and the allowPartialResults flag. 7. Response-phase plugins – executed after aggregation, can modify headers or the response body. 8. Response writing – writes the aggregated response, appropriate HTTP status code, and headers to the client.

Status code determination:

- 200 OK: all upstreams succeeded, no errors. - 206 Partial Content: allowPartialResults=true, at least one upstream failed. - 500 Internal Server Error: allowPartialResults=false, at least one upstream failed.

The final response always includes a JSON body with `data` and `errors` fields, and a `X-Request-ID` header.

type RouterConfigSet

type RouterConfigSet struct {
	Version     string
	Routes      []RouteConfig
	Middlewares []MiddlewareConfig
	Features    []FeatureConfig
	Metrics     MetricsConfig
}

type ServerConfig

type ServerConfig struct {
	Port    int           `json:"port" yaml:"port" toml:"port" validate:"required,min=1,max=65535"`
	Timeout time.Duration `json:"timeout" yaml:"timeout" toml:"timeout"`
	Metrics MetricsConfig `json:"metrics" yaml:"metrics" toml:"metrics"`
}

type Upstream

type Upstream interface {
	Name() string
	Policy() Policy
	Call(ctx context.Context, original *http.Request, originalBody []byte) *UpstreamResponse
}

type UpstreamConfig

type UpstreamConfig struct {
	Name                string        `json:"name" yaml:"name" toml:"name"`
	Hosts               []string      `json:"hosts" yaml:"hosts" toml:"hosts" validate:"required,hosts"`
	Method              string        `json:"method" yaml:"method" toml:"method" validate:"required"`
	Timeout             time.Duration `json:"timeout" yaml:"timeout" toml:"timeout"`
	ForwardHeaders      []string      `json:"forward_headers" yaml:"forward_headers" toml:"forward_headers"`
	ForwardQueryStrings []string      `json:"forward_query_strings" yaml:"forward_query_strings" toml:"forward_query_strings"`
	Policy              PolicyConfig  `json:"policy" yaml:"policy" toml:"policy"`
}

type UpstreamError

type UpstreamError struct {
	Kind UpstreamErrorKind // Error kind for aggregator.
	Err  error             // Original error. Not for client!
}

func (*UpstreamError) Error

func (ue *UpstreamError) Error() string

Error returns the upstream error kind. Error kind is a custom string type, not error interface!

func (*UpstreamError) Unwrap

func (ue *UpstreamError) Unwrap() error

Unwrap returns the original error.

type UpstreamErrorKind

type UpstreamErrorKind string
const (
	UpstreamTimeout      UpstreamErrorKind = "timeout"
	UpstreamCanceled     UpstreamErrorKind = "canceled"
	UpstreamConnection   UpstreamErrorKind = "connection"
	UpstreamBadStatus    UpstreamErrorKind = "bad_status"
	UpstreamReadError    UpstreamErrorKind = "read_error"
	UpstreamBodyTooLarge UpstreamErrorKind = "body_too_large"
	UpstreamCircuitOpen  UpstreamErrorKind = "circuit_open"
	UpstreamInternal     UpstreamErrorKind = "internal"
)

type UpstreamResponse

type UpstreamResponse struct {
	Status  int
	Headers http.Header
	Body    []byte
	Err     *UpstreamError
}

type VictoriaMetricsConfig

type VictoriaMetricsConfig struct {
	Host     string        `json:"host" yaml:"host" toml:"host"`
	Port     int           `json:"port" yaml:"port" toml:"port"`
	Path     string        `json:"path" yaml:"path" toml:"path"`
	Interval time.Duration `json:"interval" yaml:"interval" toml:"interval"`
}

Directories

Path Synopsis
builtin
cmd
kono command
internal
app

Jump to

Keyboard shortcuts

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