Documentation
ΒΆ
Overview ΒΆ
Package ikuaiapi provides a Go SDK for interacting with iKuai routers using the local v4.0 REST API.
The SDK uses the Go standard library net/http with a small custom layer (retry + timeout + sanitization) and exposes a typed service layer per functional area (system, network, firewall, monitor, ...).
Authentication uses a Bearer token obtained from the router web UI (System β Auth β API Token). iKuai OS v4.x exposes all router configuration under /api/v4.0/*.
Basic usage:
client, err := ikuaiapi.NewClient("https://192.168.1.1",
ikuaiapi.WithToken("<router-api-token>"),
)
if err != nil {
log.Fatal(err)
}
defer client.Close()
api := service.NewAPIClient(client)
iface, err := api.Network().GetInterfaces(ctx)
Package version: the iKuai API only supports the v4 REST surface.
Index ΒΆ
- Constants
- Variables
- func SanitizeNil(body []byte) []byte
- func ValidateToken(token string) error
- type APIError
- type APIErrorDetail
- type Client
- func (c *Client) Close()
- func (c *Client) Delete(ctx context.Context, p string, body any) (json.RawMessage, error)
- func (c *Client) Do(ctx context.Context, method, p string, body, out any) error
- func (c *Client) FormatQuery(q map[string]string) string
- func (c *Client) Get(ctx context.Context, p string, params map[string]string) (json.RawMessage, error)
- func (c *Client) Metrics() *Metrics
- func (c *Client) Patch(ctx context.Context, p string, body any) (json.RawMessage, error)
- func (c *Client) Post(ctx context.Context, p string, body any) (json.RawMessage, error)
- func (c *Client) Put(ctx context.Context, p string, body any) (json.RawMessage, error)
- type ClientOption
- func WithAPIBase(base string) ClientOption
- func WithDryRun(dry bool) ClientOption
- func WithHTTPClient(h *http.Client) ClientOption
- func WithInsecureSkipVerify(skip bool) ClientOption
- func WithLogger(fn func(format string, args ...any)) ClientOption
- func WithMetrics(m *Metrics) ClientOption
- func WithRawMode(raw bool) ClientOption
- func WithRetry(retryMax int) ClientOption
- func WithRetryDelay(base, max time.Duration) ClientOption
- func WithStructuredLogger(l Logger) ClientOption
- func WithTimeout(d time.Duration) ClientOption
- func WithToken(token string) ClientOption
- type LogLevel
- type Logger
- type Metrics
- type NetworkError
- type V4Endpoint
- type Version
Constants ΒΆ
const SDKVersion = "1.1.1"
SDKVersion is the semantic version of this SDK.
const TokenHelp = "obtain a token from the router web UI (System β Auth β API Token)"
TokenHelp is a short, copy-pasteable instruction for obtaining a token from an iKuai router web UI. The SDK does not log in on behalf of the caller: tokens are generated manually in System β Auth β API Token.
const V4APIBase = "/api/v4.0"
V4APIBase is the canonical root for all iKuai v4 REST endpoints.
Variables ΒΆ
var V4EndpointCatalog = []V4Endpoint{}/* 151 elements not displayed */
Functions ΒΆ
func SanitizeNil ΒΆ
SanitizeNil replaces bare `nil` tokens in JSON value positions with `null`. Some iKuai firmware emits `nil` instead of `null`; the function tracks string state to avoid corrupting legitimate string content.
func ValidateToken ΒΆ
ValidateToken returns an error if the token looks malformed. iKuai router tokens are 32-character lowercase hex strings.
Types ΒΆ
type APIError ΒΆ
type APIError struct {
HTTPStatus int
Code int
Message string
Details []APIErrorDetail
// RetryAfter, when non-zero, carries a server-advised back-off hint
// (parsed from the HTTP Retry-After header, typically on 429/503).
RetryAfter time.Duration
}
APIError is returned when the router replies with a non-success envelope or an HTTP 4xx/5xx status. It is the only typed error the SDK raises for protocol-level failures; transport failures come back as *NetworkError.
func (*APIError) IsRetryable ΒΆ added in v1.1.0
IsRetryable on an *APIError reflects server-side retryability.
type APIErrorDetail ΒΆ
type Client ΒΆ
type Client struct {
BaseURL string
Token string
APIBase string
HTTPClient *http.Client
UserAgent string
// RawMode returns the full JSON envelope (data/results/rowid/code/message)
// instead of just the data field. Useful for debugging.
RawMode bool
// DryRun reports the request it would have made without contacting the
// router. Read methods return the preview as a JSON object, write
// methods return without executing.
DryRun bool
// Logger, if set, receives short human-readable status lines.
Logger func(format string, args ...any)
// contains filtered or unexported fields
}
Client is the iKuai HTTP API client.
func NewClient ΒΆ
func NewClient(baseURL string, opts ...ClientOption) (*Client, error)
NewClient creates a Client targeting the given router. baseURL should be of the form "http://192.168.1.1" or "https://router.lan:443".
func (*Client) Close ΒΆ
func (c *Client) Close()
Close releases the underlying transport. Safe to call multiple times.
func (*Client) Do ΒΆ
Do executes a typed REST call and decodes the result into out (which may be nil for requests that only return a rowid/message).
func (*Client) FormatQuery ΒΆ added in v1.0.1
FormatQuery is exported for callers that need to assemble a query string from a map (e.g. the Call escape hatch appends ?key=value to the path for DELETE requests that iKuai drives with query params).
func (*Client) Get ΒΆ
func (c *Client) Get(ctx context.Context, p string, params map[string]string) (json.RawMessage, error)
Get issues a GET request. params is optional and added to the query string.
func (*Client) Metrics ΒΆ added in v1.1.0
Metrics returns the attached Metrics collector, or nil if none was set.
type ClientOption ΒΆ
type ClientOption func(*Client)
ClientOption configures a Client at construction time.
func WithAPIBase ΒΆ
func WithAPIBase(base string) ClientOption
WithAPIBase overrides the default /api/v4.0 prefix.
func WithDryRun ΒΆ
func WithDryRun(dry bool) ClientOption
WithDryRun reports the request it would have made without contacting the router.
func WithHTTPClient ΒΆ
func WithHTTPClient(h *http.Client) ClientOption
WithHTTPClient replaces the underlying *http.Client. Callers that need proxy, custom CA, or tracing support can pass their own.
func WithInsecureSkipVerify ΒΆ
func WithInsecureSkipVerify(skip bool) ClientOption
WithInsecureSkipVerify disables TLS certificate verification. iKuai routers use self-signed certificates by default, so this is normally the desired behaviour. Use only on trusted networks.
func WithLogger ΒΆ
func WithLogger(fn func(format string, args ...any)) ClientOption
WithLogger sets a logging callback. The callback is invoked once per request with a short status line. Prefer WithStructuredLogger for new code.
func WithMetrics ΒΆ added in v1.1.0
func WithMetrics(m *Metrics) ClientOption
WithMetrics attaches a Metrics collector. When set, every request records its duration and outcome (see Metrics.RecordRequest). Use GetStats to read counters, e.g. for a /metrics endpoint or health check.
func WithRawMode ΒΆ
func WithRawMode(raw bool) ClientOption
WithRawMode enables envelope-level responses (see Client.RawMode).
func WithRetry ΒΆ
func WithRetry(retryMax int) ClientOption
WithRetry configures exponential-back-off retries. retryMax is the total attempt count (initial + retries). The default is 3.
func WithRetryDelay ΒΆ
func WithRetryDelay(base, max time.Duration) ClientOption
WithRetryDelay sets the base delay and maximum delay for retries.
func WithStructuredLogger ΒΆ added in v1.1.0
func WithStructuredLogger(l Logger) ClientOption
WithStructuredLogger attaches a leveled, structured Logger (see logger.go). When set, retry / timeout / token-failure events are emitted through it instead of the printf-style Logger callback.
func WithTimeout ΒΆ
func WithTimeout(d time.Duration) ClientOption
WithTimeout sets the per-request timeout. The same value is also used as the overall upper bound for retried requests.
func WithToken ΒΆ
func WithToken(token string) ClientOption
WithToken sets the Bearer token used on every request.
type Logger ΒΆ
type Logger interface {
Debug(msg string, args ...interface{})
Info(msg string, args ...interface{})
Warn(msg string, args ...interface{})
Error(msg string, args ...interface{})
}
func NewDefaultLogger ΒΆ
type Metrics ΒΆ
type Metrics struct {
// contains filtered or unexported fields
}
func NewMetrics ΒΆ
func NewMetrics() *Metrics
func (*Metrics) RecordRequest ΒΆ
type NetworkError ΒΆ
NetworkError wraps connection-level failures (DNS, refused, TLS, timeout).
func (*NetworkError) Error ΒΆ
func (e *NetworkError) Error() string
func (*NetworkError) IsRetryable ΒΆ added in v1.1.0
func (e *NetworkError) IsRetryable() bool
IsRetryable reports whether a caller may safely retry the request that produced this error. It encodes the SDK's own retry policy so applications can reuse it for custom retry loops or circuit-breaker decisions.
- *NetworkError: retryable (transport hiccups usually clear up), but only for idempotent verbs β the SDK never auto-retries a write on a network error because the request may have reached the router.
- *APIError: retryable on HTTP 429 (rate limited), 5xx, and gateway errors. 4xx (other than 429) are not retryable.
Pass the HTTP method to qualify network errors: IsRetryable on a *NetworkError returns false for POST/PUT/PATCH to avoid duplicate writes.
func (*NetworkError) Unwrap ΒΆ
func (e *NetworkError) Unwrap() error
type V4Endpoint ΒΆ
type V4Endpoint struct {
Group string
Name string
Path string
Methods []string
// Load marks monitoring load-style endpoints. Such endpoints accept
// datetype/start_time/end_time/math query params rather than the
// usual page/page_size/filter/order/order_by. The codegen emits a
// typed <Name>LoadOptions struct plus enum validation for these.
Load bool
// Action is the verb suffix for action-style endpoints (those whose
// path ends with ":start", ":stop", ":restart", ":sync", ":restore",
// ":check"). The codegen uses this to emit semantically named
// helpers (Start<Name>, Stop<Name>, Restore<Name>, etc.) instead of
// a generic Do<Name>. Empty means the endpoint follows the standard
// CRUD shape.
Action string
}
func V4EndpointByGroupName ΒΆ
func V4EndpointByGroupName(group, name string) (V4Endpoint, bool)
V4EndpointByGroupName resolves an endpoint by its (group, name) pair. Use this when the same Name appears under multiple Groups (e.g. "system" exists in both "log" and "monitoring").
func V4EndpointByName ΒΆ
func V4EndpointByName(name string) (V4Endpoint, bool)