Documentation
¶
Overview ¶
Package-level client wiring: the Client type, its options, and the verb methods. Response handling lives in envelope.go, the retry engine in retry.go, dry-run previews in dryrun.go.
Package ikuaiapi is a Go SDK for the iKuai v4.0 REST API — the local management API exposed by routers running iKuai OS 4.x.
Getting started ¶
Obtain an API token in the router web UI (System -> Auth -> API Token), then build a client. Everything else hangs off the typed service layer.
client, err := ikuaiapi.NewClient("https://192.168.1.1",
ikuaiapi.WithToken(token),
ikuaiapi.WithTimeout(15*time.Second),
)
if err != nil {
return err
}
defer client.Close(context.Background())
api := service.NewAPIClient(client)
sys, err := api.Monitoring().GetMonitoringSystem(ctx)
Credentials can also come from a session file or the environment; see the session package.
The v4 API is not uniform ¶
Two facts shape most of this SDK's design, and both are learned the hard way from real hardware:
- The page-size query parameter is named limit, not page_size. Sending page_size makes the router ignore the whole paging query, silently, so a "paged" read quietly returns everything.
- Collections do not all speak the same query dialect. Most take page/limit/filter/order/order_by, but several monitoring endpoints want an uppercase TYPE/LIMIT/OFFSET form, /auth/online-users mixes lowercase paging with uppercase search keys, and a family of endpoints uses starttime/stoptime. Sending the wrong shape is also silently ignored.
Both are encoded in the catalog rather than left to the caller. Each endpoint records its dialect in V4Endpoint.Query, and the generated service layer exposes a typed Query<Name> helper for the endpoints that need one. See v4_catalog.go and skills/SKILL.md.
Writing ¶
The firmware validates writes strictly and, for most rule-like resources, rejects a partial update rather than filling the gaps with its own defaults — which silently reconfigures whatever the caller left out. V4Schemas records each endpoint's create defaults, update allowlist and required fields; CreateBody and UpdatePayload apply them. See fields.go and skills/writing.md.
Errors ¶
Errors follow the oekit contract, so an error raised here is understood by an oekit service without an adapter. Every APIError carries an oekit BizError: the iKuai code becomes the business code, and an expired token (3007) answers 401, a permission failure (10014) answers 403, and a bad payload (3001) answers 400. A handler calling errors.As, including oekit's middleware.Fail, sees those codes rather than a generic 500.
var apiErr *ikuaiapi.APIError
if errors.As(err, &apiErr) {
switch {
case apiErr.IsAuthFailure(): // refresh the token
case apiErr.IsPermissionFailure(): // needs a privileged account
case apiErr.IsBadRequest(): // fix the payload
}
log.Println(apiErr.Message, "->", apiErr.Remedy())
}
SDK-local validation failures use the 4xxx business-code band, so a caller can tell "the SDK refused to send this" from "the router said no".
Logging ¶
The SDK logs through the oekit logx facade with a lazily resolved package logger, so it never picks a backend or a service name on behalf of its consumer: call logx.SetDefault, logx.UseSlog, or install an hlog backend in main, and this package follows. SetLogLevel controls the floor for the SDK's own events.
What it emits is request metadata — method, URL, retry count, delay — and never the bearer token. If a URL is itself sensitive on your network, wrap the facade before installing it and redact by key:
logx.SetDefault(logx.WithFilter(logx.UseSlog("svc")).
logx.FilterKey("url"), logx.FilterKey("path"),
)
Observability ¶
Metrics collects request counts and latency without forcing a metrics backend on a consumer. Retry honours Retry-After, and never retries a write on a transport error, because that write may already have reached the router.
Packages ¶
- service — the generated typed client, one service per endpoint group.
- session — credential persistence and resolution.
- output — table and JSON rendering for responses.
Package version: the iKuai API only supports the v4 REST surface.
Index ¶
- Constants
- Variables
- func AddressValues(values ...string) map[string]any
- func AsBizError(err error) (*oekerrors.BizError, bool)
- func CodeFor(ikuaiCode int) int
- func CoerceBody(body map[string]any) map[string]any
- func CreateBody(path string, overrides map[string]any) (map[string]any, error)
- func Enabled(v bool) string
- func FirstObject(raw json.RawMessage) (map[string]any, error)
- func IntegerAPIFields() map[string]bool
- func IsIntegerAPIField(name string) bool
- func MergeBody(existing, updates map[string]any) map[string]any
- func ObjectGroup(group string, values ...string) ([]any, error)
- func ParseEnabled(s string) (bool, error)
- func ParseQuerySpec(spec string) (QueryDialect, []QueryField, []QueryField, error)
- func SanitizeNil(body []byte) []byte
- func SchemaPaths() []string
- func SetLogLevel(l LogLevel)
- func StatusFor(ikuaiCode, routerStatus int) int
- func TimeObjectGroup(scheduleType, weekdays, startTime, endTime, comment string) map[string]any
- func UpdateFields(path string) []string
- func UpdatePayload(ctx context.Context, c *Client, path string, id int64, updates map[string]any, ...) (map[string]any, error)
- func ValidateToken(token string) error
- func WeekSchedule() map[string]any
- type APIError
- func (e *APIError) Biz() *oekerrors.BizError
- func (e *APIError) Error() string
- func (e *APIError) IsAuthFailure() bool
- func (e *APIError) IsBadRequest() bool
- func (e *APIError) IsPermissionFailure() bool
- func (e *APIError) IsRetryable() bool
- func (e *APIError) Remedy() string
- func (e *APIError) Unwrap() error
- type APIErrorDetail
- type Client
- func (c *Client) Close(ctx context.Context) error
- 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 WithMetrics(m *Metrics) ClientOption
- func WithRawMode(raw bool) ClientOption
- func WithRetry(retryMax int) ClientOption
- func WithRetryDelay(base, max time.Duration) ClientOption
- func WithStructuredLogger(l logx.Logger) ClientOption
- func WithTimeout(d time.Duration) ClientOption
- func WithToken(token string) ClientOption
- type ErrorOption
- type LogLevel
- type Metrics
- type MirrorRule
- type NetworkError
- type QueryDialect
- type QueryField
- type V4Endpoint
- type V4Schema
- type Version
Constants ¶
const SDKVersion = "1.3.3"
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 TokenLength = 32
TokenLength is the character length of an iKuai API token, in both of the shapes firmware has shipped.
const V4APIBase = "/api/v4.0"
V4APIBase is the canonical root for all iKuai v4 REST endpoints.
Variables ¶
var ( // ErrRequiredField reports a missing required body field. ErrRequiredField = oekerrors.New("ikuaiapi: required field missing") // ErrUnknownObjectGroup reports an object group name the SDK does not // know how to encode. ErrUnknownObjectGroup = oekerrors.New("ikuaiapi: unknown object group") // ErrNoSchema reports that no body contract is recorded for a path. ErrNoSchema = oekerrors.New("ikuaiapi: no schema recorded for path") // ErrEmptyResponse reports a response with nothing to decode. ErrEmptyResponse = oekerrors.New("ikuaiapi: empty response") // ErrNoObject reports a response that decoded but held no object. ErrNoObject = oekerrors.New("ikuaiapi: response contains no object") )
Sentinel errors for the SDK's own pre-flight validation. Router-side failures always come back as *APIError.
var ErrInvalidToken = oekerrors.New("ikuaiapi: invalid token")
ErrInvalidToken is returned when a token fails format validation. It is a sentinel so callers can match it with errors.Is.
var ErrNotConfigured = oekerrors.New("ikuaiapi: baseURL is required")
ErrNotConfigured is returned when a client is constructed without a base URL, which is the one value with no sensible default.
var V4EndpointCatalog = []V4Endpoint{}/* 157 elements not displayed */
V4EndpointCatalog is the verified inventory of the v4 API.
Paths here were checked against iKuai OS 4.x hardware, and several entries exist because a probe proved the obvious spelling wrong:
- VPN server configuration lives at /vpn/<proto>/services. The bare /vpn/<proto> answers 404.
- The IPv6 and protocol object groups are /ip6-objects and /proto-objects. /ipv6-objects and /protocol-objects answer 404.
- The page-size query parameter is "limit". "page_size" is accepted and ignored: the router returns every row, so paging silently does nothing.
- Every collection uses order=<direction> and order_by=<field>. Swapping the two returns no rows at all, on security collections included.
- Four AC entries used to sit at the API root (/services, /clients, /peers, /ref). All four 404. The controller's real endpoints are /network/ac/services and /network/ac/ap-config, which the network group already carried.
A 404 here means the path is wrong, not that the feature is absent: the router answers an unknown path with an HTML 404 body rather than the usual JSON envelope.
var V4Schemas = map[string]V4Schema{ "/security/acl-rules": { CreateDefaults: map[string]any{ "enabled": "yes", "ip_type": "4", "ctdir": 0, "dir": "forward", "iinterface": "any", "ointerface": "any", "prio": 50, "comment": "", "src_addr": selectorPair(), "dst_addr": selectorPair(), "src_port": selectorPair(), "dst_port": selectorPair(), "src_addr_inv": 0, "dst_addr_inv": 0, "src_type": 0, "dst_type": 0, "src_area_code": "", "dst_area_code": "", "src6_addr": selectorPair(), "dst6_addr": selectorPair(), "src6_mode": 0, "dst6_mode": 0, "src6_suffix": "", "dst6_suffix": "", "time": weeklyWindow(), }, RequiredFields: []string{"tagname", "action", "protocol"}, }, "/security/app-protocols/professional/rules": { CreateDefaults: map[string]any{ "enabled": "yes", "comment": "", "app_proto": selectorPair(), "src_addr": "", "dst_addr": "", "time": weeklyWindow(), }, RequiredFields: []string{"tagname", "action", "prio", "app_proto"}, }, "/security/mac-rules": { CreateDefaults: map[string]any{ "enabled": "yes", "expires": 0, "comment": "", "time": weeklyWindow(), }, RequiredFields: []string{"tagname", "mac"}, }, "/security/url-black/rules": { CreateDefaults: map[string]any{ "enabled": "yes", "comment": "", "domain": selectorPair(), "src_addr": selectorPair(), "time": selectorPair(), }, RequiredFields: []string{"tagname", "mode", "domain"}, }, "/security/url-keywords/rules": { CreateDefaults: map[string]any{"enabled": "yes"}, RequiredFields: []string{"tagname", "mode", "src_url", "ori_keyword", "rep_keyword", "hit_rate", "prio"}, }, "/security/url-redirect/rules": { CreateDefaults: map[string]any{"enabled": "yes"}, RequiredFields: []string{"tagname", "mode", "src_url", "dst_url", "hit_rate", "prio"}, }, "/security/url-replace/rules": { CreateDefaults: map[string]any{"enabled": "yes"}, RequiredFields: []string{"tagname", "mode", "src_url", "param_keyword", "rep_keyword", "hit_rate", "prio"}, }, "/security/domain-blacklist/rules": { CreateDefaults: map[string]any{"enabled": "yes"}, RequiredFields: []string{"tagname", "domain_group"}, }, "/security/peerconn/rules": { CreateDefaults: map[string]any{ "enabled": "yes", "comment": "", "src_addr": selectorPair(), "dst_port": selectorPair(), }, RequiredFields: []string{"tagname", "limits", "protocol"}, }, "/security/terminals": { RequiredFields: []string{"tagname", "mac"}, }, "/routing/static-routes": { CreateDefaults: map[string]any{ "enabled": "yes", "ip_type": "4", "comment": "", "prio": 1, }, DropSuffix: []string{"_int"}, NormalizeSelectors: true, RequiredFields: []string{ "tagname", "dst_addr", "gateway", "netmask", "interface", }, }, "/network/dns/config": { InputFields: []string{ "enabled", "forbid_dns_4a", "cache_ttl", "cachemode", "proxy_force", "proxy_force_dns", "dns1", "dns2", "query", "defense", "network", "query_args_ip", "query_head_ip", }, }, "/network/dhcp/access-control/mode": { InputFields: []string{"mode"}, }, "/network/dhcp6/access-control/mode": { InputFields: []string{"mode"}, }, "/security/mac-mode": { InputFields: []string{"acl_mac"}, }, "/security/advanced/config": { InputFields: []string{ "noping_lan", "noping_wan", "notracert", "hijack_ping", "invalid", "dos_lan", "dos_lan_num", "tcp_mss", "tcp_mss_num", "limit_tcp2p", "limit_tcp2p_num", "limit_udp2p", "limit_udp2p_num", }, }, "/security/secondary-route/config": { InputFields: []string{"nol2rt", "nol2rt_ip", "ttl_num", "time"}, NormalizeSelectors: true, }, "/system/cpufreq": { InputFields: []string{"mode", "turbo"}, }, "/routing/domain-rules": { CreateDefaults: map[string]any{ "enabled": "yes", "comment": "", "prio": 31, "domain": selectorPair(), "src_addr": selectorPair(), "time": weeklyWindow(), }, RequiredFields: []string{"tagname", "interface"}, }, "/routing/five-tuple-rules": { CreateDefaults: map[string]any{ "enabled": "yes", "comment": "", "type": 0, "mode": 0, "prio": 31, "iface_band": 0, "src_addr_inv": 0, "dst_addr_inv": 0, "protocol": "any", "src_addr": selectorPair(), "dst_addr": selectorPair(), "src_port": selectorPair(), "dst_port": selectorPair(), "time": weeklyWindow(), }, RequiredFields: []string{"tagname", "interface"}, }, "/routing/app-protocols": { CreateDefaults: map[string]any{ "enabled": "yes", "comment": "", "app_proto": selectorPair(), "mode": 0, "prio": 31, "iface_band": 0, "src_addr": selectorPair(), "time": weeklyWindow(), }, RequiredFields: []string{"tagname", "interface"}, }, "/routing/load-balance-rules": { CreateDefaults: map[string]any{ "enabled": "yes", "comment": "", "mode": 0, "weight": "1", "isp_name": "all", }, RequiredFields: []string{"tagname", "interface"}, }, "/routing/updown": { CreateDefaults: map[string]any{ "enabled": "yes", "comment": "", "protocol": "any", "src_addr": selectorPair(), "dst_addr": selectorPair(), "src_port": selectorPair(), "dst_port": selectorPair(), }, RequiredFields: []string{"tagname", "upiface", "downiface"}, }, "/network/qos/ip": { CreateDefaults: map[string]any{ "enabled": "yes", "comment": "", "type": 0, "protocol": "any", "ip_addr": selectorPair(), "src_port": selectorPair(), "dst_port": selectorPair(), "time": weeklyWindow(), }, RequiredFields: []string{"tagname", "interface", "upload", "download"}, }, "/network/qos/mac": { CreateDefaults: map[string]any{ "enabled": "yes", "comment": "", "type": 0, "ip_type": "4", "time": weeklyWindow(), }, RequiredFields: []string{"tagname", "interface", "upload", "download"}, }, "/network/nat/rules": { CreateDefaults: map[string]any{ "enabled": "yes", "comment": "", "protocol": "", "nat_addr": "", "nat_port": "", "src_addr": selectorPair(), "dst_addr": selectorPair(), "src_port": selectorPair(), "dst_port": selectorPair(), "src_addr_inv": 0, "dst_addr_inv": 0, }, InputFields: []string{ "tagname", "enabled", "action", "iinterface", "ointerface", "src_addr", "dst_addr", "nat_addr", "nat_port", "protocol", "comment", "src_port", "dst_port", "src_addr_inv", "dst_addr_inv", }, RequiredFields: []string{"tagname", "action", "iinterface", "ointerface"}, }, "/network/dnat/rules": { CreateDefaults: map[string]any{ "enabled": "yes", "comment": "", "src_addr": selectorPair(), }, InputFields: []string{ "id", "tagname", "enabled", "lan_addr", "lan_port", "protocol", "interface", "wan_port", "src_addr", "comment", }, RequiredFields: []string{"tagname", "lan_addr", "lan_port", "wan_port", "protocol", "interface"}, DropSuffix: []string{"_int"}, }, "/network/dmz/rules": { CreateDefaults: map[string]any{"enabled": "yes", "comment": ""}, InputFields: []string{ "id", "tagname", "enabled", "interface", "lan_addr", "protocol", "excl_port", "comment", }, RequiredFields: []string{"tagname", "interface", "lan_addr", "protocol", "excl_port"}, DropSuffix: []string{"_int"}, }, "/network/dns/proxy/rules": { CreateDefaults: map[string]any{ "enabled": "yes", "comment": "", "src_addr": "", }, RequiredFields: []string{"domain", "dns_addr", "parse_type"}, }, "/network/vlan": { CreateDefaults: map[string]any{ "enabled": "yes", "mac": "", "ip_mask": "", "comment": "", }, Mirror: []MirrorRule{ {From: "vlan_name", To: "tagname", Overwrite: true}, }, InputFields: []string{ "vlan_id", "vlan_name", "tagname", "interface", "mac", "ip_addr", "netmask", "ip_mask", "enabled", "comment", }, RequiredFields: []string{"vlan_id", "vlan_name", "interface", "ip_addr", "netmask"}, }, "/network/pppoe/services": { CreateDefaults: map[string]any{ "server_name": "iKuai", "force_verify_name": 0, "nas_identifier": "iKuai", "nas_ip_address": "", "authport": 1812, "accountport": 1813, "rate_limit_lan": 1, "drop_client": 1, "force_pppoe": 0, "enhance_check": 1, "share_deny": 0, "bind_vlan": 0, "verify_vlan": 1, "bind_iface": 0, "mtu": 1480, "mru": 1480, "lcp_echo_interval": 10, "lcp_echo_failure": 3, "maxconnect": 0, "restart_timer": 0, "comment": "", }, InputFields: []string{ "enabled", "server_name", "force_verify_name", "server_ip", "dns1", "dns2", "authmode", "nas_identifier", "nas_ip_address", "radius_ip", "secret", "authport", "accountport", "addr_pool", "interface", "rate_limit_lan", "drop_client", "force_pppoe", "enhance_check", "share_deny", "bind_vlan", "verify_vlan", "bind_iface", "mtu", "mru", "lcp_echo_interval", "lcp_echo_failure", "maxconnect", "restart_timer", "restart_week", "restart_time", "comment", }, }, "/network/dhcp6/access-control/rules": { InputFields: []string{"enabled", "mac", "tagname", "comment"}, RequiredFields: []string{"tagname", "mac"}, }, "/network/dhcp/access-control/rules": { CreateDefaults: map[string]any{"enabled": "yes", "comment": ""}, InputFields: []string{"enabled", "mac", "tagname", "comment"}, RequiredFields: []string{"tagname", "mac"}, }, "/network/dhcp/services": { CreateDefaults: map[string]any{ "enabled": "yes", "delay": 0, "check_addr_valid": 0, "check_relay_only": 0, }, UpdateDefaults: map[string]any{ "opt_type15": 0, "opt_type28": 0, "opt_type43": 0, "opt_type60": 0, "opt_type66": 0, "opt_type67": 0, "opt_type80": 0, "opt_type119": 0, "opt_type125": 0, "opt_type128": 0, "opt_type138": 0, "opt_type121": 2, }, InputFields: []string{ "enabled", "tagname", "interface", "phy_ifnames", "addr_pool", "exclude_pool", "netmask", "gateway", "dns1", "dns2", "wins1", "wins2", "domain", "next_server", "lease", "delay", "opt_type15", "opt15", "opt_type28", "opt28", "opt_type43", "opt43", "opt_type60", "opt60", "opt_type66", "opt66", "opt_type67", "opt67", "opt_type80", "opt80", "opt_type119", "opt119", "opt_type125", "opt125", "opt_type128", "opt128", "opt_type138", "opt138", "opt_type121", "opt121", "check_addr_valid", "check_relay_only", }, RequiredFields: []string{ "tagname", "interface", "phy_ifnames", "addr_pool", "netmask", "gateway", "lease", }, DropBlanks: []string{ "opt_type15", "opt_type28", "opt_type43", "opt_type60", "opt_type66", "opt_type67", "opt_type80", "opt_type119", "opt_type125", "opt_type128", "opt_type138", "opt_type121", }, }, "/network/dhcp/static": { CreateDefaults: map[string]any{"enabled": "yes"}, InputFields: []string{ "enabled", "mac", "ip_addr", "interface", "gateway", "dns1", "dns2", "comment", "tagname", "hostname", "termname", }, DropSuffix: []string{"_int"}, RequiredFields: []string{"mac", "ip_addr", "interface", "tagname"}, }, "/ip-objects": { InputFields: []string{"group_name", "group_value"}, RequiredFields: []string{"group_name"}, }, "/ip6-objects": { InputFields: []string{"group_name", "group_value"}, RequiredFields: []string{"group_name"}, }, "/mac-objects": { InputFields: []string{"group_name", "group_value"}, RequiredFields: []string{"group_name"}, }, "/port-objects": { InputFields: []string{"group_name", "group_value"}, RequiredFields: []string{"group_name"}, }, "/proto-objects": { InputFields: []string{"group_name", "group_value"}, RequiredFields: []string{"group_name"}, }, "/domain-objects": { InputFields: []string{"group_name", "group_value"}, RequiredFields: []string{"group_name"}, }, "/time-objects": { InputFields: []string{"group_name", "group_value"}, RequiredFields: []string{"group_name"}, }, "/wireless/access-control/rules": { CreateDefaults: map[string]any{ "enabled": "yes", "mode": 0, "lmac": selectorPair(), "lssid": "ALL", "lap": "ALL", "week": "1234567", "time": "00:00-23:59", "comment": "", }, InputFields: []string{ "enabled", "tagname", "mode", "lmac", "lssid", "lap", "week", "time", "comment", }, RequiredFields: []string{"tagname"}, }, "/wireless/vlan/rules": { CreateDefaults: map[string]any{ "enabled": "yes", "lssid": "ALL", "lmac": selectorPair(), "comment": "", }, InputFields: []string{"enabled", "tagname", "vlanid", "lmac", "lssid", "comment"}, RequiredFields: []string{"tagname", "vlanid"}, }, "/vpn/pptp/clients": { CreateDefaults: map[string]any{ "enabled": "yes", "comment": "", "server_port": 1723, "mtu": 1400, "mru": 1400, "check_link_mode": 3, "check_link_host": "www.baidu.com", "timing_rst_switch": 0, "timing_rst_week": "1234567", "timing_rst_time": "12:00", "cycle_rst_time": 0, }, InputFields: []string{ "id", "enabled", "name", "comment", "server", "server_port", "username", "passwd", "interface", "mtu", "mru", "check_link_mode", "check_link_host", "timing_rst_switch", "timing_rst_week", "timing_rst_time", "cycle_rst_time", }, RequiredFields: []string{"name", "server", "username", "passwd", "interface"}, }, "/vpn/l2tp/clients": { CreateDefaults: map[string]any{ "enabled": "yes", "comment": "", "server_port": 1701, "mtu": 1400, "mru": 1400, "check_link_mode": 3, "check_link_host": "www.baidu.com", "timing_rst_switch": 0, "cycle_rst_time": 0, }, InputFields: []string{ "id", "enabled", "name", "comment", "server", "server_port", "username", "passwd", "ipsec_secret", "interface", "leftid", "rightid", "mtu", "mru", "check_link_mode", "check_link_host", "timing_rst_switch", "timing_rst_week", "timing_rst_time", "cycle_rst_time", }, RequiredFields: []string{"name", "server", "username", "passwd", "interface"}, }, "/vpn/openvpn/clients": { CreateDefaults: map[string]any{ "enabled": "yes", "comment": "", "remote_port": "1194", "method": 0, "proto": "udp", "dev_type": "tun", "cipher": "BF-CBC", "tun_mtu": "1400", "comp_lzo": "1", "accept_push_route": 1, "check_link_mode": 3, "check_link_host": "www.baidu.com", "timing_rst_switch": 0, "ca": "", }, InputFields: []string{ "id", "enabled", "name", "comment", "remote_addr", "remote_port", "method", "username", "password", "interface", "proto", "dev_type", "cipher", "tls_auth", "ca", "cert", "key", "accept_push_route", "route", "comp_lzo", "tun_mtu", "check_link_mode", "check_link_host", "timing_rst_switch", "timing_rst_week", "timing_rst_time", "extra_config", }, RequiredFields: []string{"name", "remote_addr", "interface", "username", "password", "ca"}, }, "/vpn/ikev2/clients": { CreateDefaults: map[string]any{ "enabled": "yes", "comment": "", "authby": "mschapv2", "check_link_mode": 3, "check_link_host": "www.baidu.com", }, InputFields: []string{ "id", "enabled", "name", "comment", "remote_addr", "interface", "authby", "secret", "leftid", "rightid", "username", "passwd", "check_link_mode", "check_link_host", }, RequiredFields: []string{"name", "remote_addr", "interface", "leftid"}, }, "/vpn/ipsec/clients": { CreateDefaults: map[string]any{ "enabled": "yes", "comment": "", "keyexchange": "ikev2", "authby": "secret", "dpdaction": "none", "compress": "0", "ikelifetime": 3, "lifetime": 1, "ike_enc": "aes256", "ike_auth": "sha256", "ike_dh": "modp2048", "esp_enc": "aes256", "esp_auth": "sha256", "aggressive": "0", }, InputFields: []string{ "id", "name", "comment", "remote_addr", "authby", "leftsubnet", "rightsubnet", "interface", "enabled", "keyexchange", "aggressive", "ikelifetime", "ike_enc", "ike_auth", "ike_dh", "secret", "leftid", "rightid", "privatekey", "leftcert", "rightcert", "lifetime", "esp_enc", "esp_auth", "dpdaction", "dpddelay", "dpdtimeout", "compress", }, RequiredFields: []string{"name", "interface", "leftsubnet", "rightsubnet"}, }, "/vpn/wireguard": { CreateDefaults: map[string]any{ "enabled": "yes", "interface": "auto", "local_listenport": 5000, "mtu": 1420, }, InputFields: []string{ "enabled", "name", "interface", "local_privatekey", "local_publickey", "local_address", "local_listenport", "mtu", }, RequiredFields: []string{"name", "local_address", "local_privatekey", "local_publickey"}, }, "/vpn/wireguard/{tunnel_id}/peers": { CreateDefaults: map[string]any{ "enabled": "yes", "comment": "", "keepalive": 0, }, InputFields: []string{ "enabled", "comment", "interface", "peer_publickey", "presharedkey", "allowips", "endpoint", "endpoint_port", "keepalive", }, RequiredFields: []string{"peer_publickey", "allowips", "interface"}, }, "/vpn/pptp/services": { InputFields: []string{ "enabled", "dns1", "dns2", "addr_pool", "open_mppe", "server_ip", "server_port", "mtu", "mru", }, }, "/vpn/l2tp/services": { InputFields: []string{ "enabled", "server_ip", "server_port", "addr_pool", "dns1", "dns2", "mtu", "mru", "ipsec_secret", "leftid", "rightid", "force_ipsec", }, }, "/vpn/openvpn/services": { InputFields: []string{ "enabled", "proto", "port", "subnet", "mask", "tun_mtu", "cipher", "comp_lzo", "dev_type", "topology", "method", "tls_auth", "ca", "cert", "key", "push_gateway", "push_route", "push_route_comment", "push_dns", "extra_config", "auth", }, }, "/vpn/ikev2/services": { InputFields: []string{ "id", "enabled", "authby", "addrpool", "secret", "leftid", "rightid", "dns1", "dns2", "share_deny", "mtu", "privatekey", "leftcert", "aggressive", "keyexchange", "name", }, }, "/auth/users": { CreateDefaults: map[string]any{ "enabled": "yes", "comment": "", "ppptype": "any", "packages": 0, "upload": 0, "download": 0, "start_time": 0, "expires": 0, "share": 1, "ip_type": 0, "auto_mac": 0, "auto_vlanid": 0, "bind_vlanid": "0", "bind_ifname": "any", "src_addr": map[string]any{"custom": map[string]any{}}, }, InputFields: []string{ "username", "passwd", "enabled", "ppptype", "packages", "upload", "download", "start_time", "expires", "share", "ip_type", "auto_mac", "auto_vlanid", "bind_vlanid", "pppname", "pppoev6_wan", "bind_ifname", "src_addr", "mac", "address", "name", "phone", "cardid", "comment", }, RequiredFields: []string{"username", "passwd"}, }, "/auth/packages": { CreateDefaults: map[string]any{"comment": ""}, InputFields: []string{"packname", "packtime", "price", "up_speed", "down_speed", "comment"}, RequiredFields: []string{"packname", "packtime", "price", "up_speed", "down_speed"}, }, "/advanced-service/ftp-users": { CreateDefaults: map[string]any{ "enabled": "yes", "upload": 0, "download": 0, }, InputFields: []string{ "enabled", "username", "passwd", "permission", "home_dir", "upload", "download", "tagname", }, RequiredFields: []string{"username", "passwd", "permission", "home_dir"}, }, "/advanced-service/http-users": { CreateDefaults: map[string]any{ "enabled": "yes", "server_name": "", "access": 1, }, InputFields: []string{ "enabled", "tagname", "http_port", "server_name", "ssl_on", "autoindex", "download", "home_dir", "access", }, RequiredFields: []string{"tagname", "http_port", "ssl_on", "autoindex", "download", "home_dir"}, }, "/advanced-service/samba-users": { CreateDefaults: map[string]any{ "enabled": "yes", "browseable": "", }, InputFields: []string{ "enabled", "username", "passwd", "name", "perm", "guest", "home_dir", "browseable", "tagname", }, RequiredFields: []string{"name", "username", "passwd", "permission", "guest", "home_dir"}, }, "/advanced-service/ftp-config": { InputFields: []string{"open_ftp", "ftp_port", "ftp_access"}, }, "/advanced-service/samba-config": { InputFields: []string{"enabled", "workgroup", "wsdd2", "access", "interface"}, }, "/advanced-service/snmpd-config": { InputFields: []string{ "enabled", "listen_port", "syslocation", "syscontact", "sysname", "version", "community", "source", "rw", "username", "security", "auth_proto", "auth_pass", "priv_proto", "priv_pass", }, }, "/system/basic/config": { InputFields: []string{ "hostname", "language", "time_zone", "time_zone_full", "switch_nat", "switch_ntp", "switch_ntpd", "switch_ntpserver", "ntpserver_list", "ntp_sync_cycle", "link_mode", "lan_nat", "backport", "listenport", "fast_nat", }, }, "/system/reboot-schedules": { CreateDefaults: map[string]any{ "enabled": "yes", "event": "reboot", "comment": "", }, InputFields: []string{ "enabled", "tagname", "event", "strategy", "cycle_time", "time", "comment", }, RequiredFields: []string{"tagname", "time", "strategy", "cycle_time"}, }, "/system/remote-access": { InputFields: []string{ "open_telnetd", "open_wanweb", "open_sshd", "sshd_port", "sshd_passwd", "http_port", "https_port", "force_https", "open_ftp", "ftp_port", "ftp_access", }, }, "/system/vrrp/config": { CreateDefaults: map[string]any{ "method": 2, "domain": "www.baidu.com", "dns": "114.114.114.114", "interval": 3, }, InputFields: []string{ "enabled", "type", "prio", "method", "domain", "dns", "gateway", "interval", "ifnames", "auto_sync", "single_line", "ignore_wanstatus", "interfaces", "virtual_ips", "ht_iface", "remote_addr", }, }, "/system/alg": { InputFields: []string{ "support_ftp", "support_tftp", "support_sip", "support_h323", "ftp_ports", "sip_ports", "tftp_ports", }, }, "/system/kernel-params": { InputFields: []string{ "bbr", "syn_recv_timeout", "syn_send_timeout", "established_timeout", "fin_wait_timeout", "last_ack_timeout", "close_wait_timeout", "time_wait_timeout", "close_timeout", "udp_timeout", "udp_stream_timeout", "icmp_timeout", }, }, "/system/cpufreq/mode": { InputFields: []string{"mode", "turbo"}, }, "/system/backup-auto": { InputFields: []string{"id", "enabled", "strategy", "time", "cycle_time", "valid_days", "tagname"}, }, "/system/web-admin/groups": { InputFields: []string{"group_name", "ip_addr", "perm_config"}, RequiredFields: []string{"ip_addr", "perm_config"}, }, "/system/web-admin/accounts": { CreateDefaults: map[string]any{ "enabled": "yes", "force": 0, "interval": 30, "sesstimeout": 120, "comment": "", }, InputFields: []string{ "username", "passwd", "enabled", "group_id", "force", "interval", "sesstimeout", "comment", }, RequiredFields: []string{"username", "passwd", "group_id"}, }, }
V4Schemas maps an endpoint path to its body contract.
Functions ¶
func AddressValues ¶ added in v1.2.0
AddressValues builds the {"custom": [...], "object": [...]} payload iKuai uses for every address, port, protocol and domain selector. The input may be a single comma-separated string or discrete values; each entry is trimmed and empty entries are dropped.
A rule with no selectors must send an empty pair rather than a bare array, which is why this returns a struct and not a []string.
func AsBizError ¶ added in v1.2.0
AsBizError extracts the oekit business error from any error chain that passes through this SDK. It is the local equivalent of oekit's errors.AsBizError and exists so callers do not have to know which layer produced the error.
func CodeFor ¶ added in v1.2.0
CodeFor maps an iKuai error code to an oekit business code. The iKuai code is itself a stable business identifier, so it is reused as-is; an unrecognized code is passed through so nothing is silently remapped.
func CoerceBody ¶ added in v1.2.0
CoerceBody normalizes a request body in place to match the firmware's expectations: every field listed in IntegerAPIFields is converted to an int64 when it can be parsed, and every other field is left as the caller supplied it. Fields that are already numbers are untouched.
It is the programmatic form of what a CLI does when it merges flags into a --data payload, and is safe to call on any map destined for Create, Update or Patch.
func CreateBody ¶ added in v1.2.0
CreateBody builds a create payload for an endpoint: every field in the endpoint's CreateDefaults, with the caller's overrides applied on top, then the result normalized for the integer fields.
The returned body is a deep copy, so mutating it — or mutating it again on a later call — cannot corrupt the shared contract.
A field listed in the endpoint's RequiredFields that the caller neither supplied nor got a default for is reported as an error, because sending an incomplete create fails in a way that looks like a network problem.
Endpoints with no recorded contract fall through to a plain merge, which keeps callers working against a router that is ahead of this table.
func Enabled ¶ added in v1.2.0
Enabled renders a Go bool the way the firmware expects it: the strings "yes" and "no", never a JSON boolean. Every rule-like resource in the catalog uses this convention for its "enabled" field.
func FirstObject ¶ added in v1.2.0
func FirstObject(raw json.RawMessage) (map[string]any, error)
FirstObject unwraps the first element of an iKuai collection response. Endpoints disagree about where the array lives — some answer with "data", some with "results", some with "data" as a single object — so callers that need one element use this instead of re-implementing the probing logic for every read-modify-write update.
func IntegerAPIFields ¶ added in v1.2.0
IntegerAPIFields returns a copy of the integer-field allowlist. It exists so callers can audit or extend the classification without reaching into the SDK's internals.
func IsIntegerAPIField ¶ added in v1.2.0
IsIntegerAPIField reports whether the named body field must be sent as a JSON number rather than a string.
func MergeBody ¶ added in v1.2.0
MergeBody merges updates over an existing object for a read-modify-write update. Keys present in updates win; every other key from existing is preserved. Passing a nil existing behaves like a plain assignment, which makes the same code path usable for create and update.
func ObjectGroup ¶ added in v1.2.0
ObjectGroup builds the group_value array for an object group. iKuai wraps every member in a single-key object named after the group type, so ObjectGroup("ip", "192.168.1.10", "192.168.1.11") produces [{"ip":"192.168.1.10"},{"ip":"192.168.1.11"}].
The time object group is the exception: its members carry named fields rather than a single value, so use TimeObjectGroup for it.
func ParseEnabled ¶ added in v1.2.0
ParseEnabled reads an iKuai enable flag. It accepts the firmware's own "yes"/"no" plus the boolean spellings that show up in payloads read back from the router, so a round-tripped value can be fed straight back in.
func ParseQuerySpec ¶ added in v1.2.0
func ParseQuerySpec(spec string) (QueryDialect, []QueryField, []QueryField, error)
ParseQuerySpec decodes the compact Query spec carried by a catalog entry.
The grammar is:
spec := clause ("+" clause)*
clause := dialect | "req:" field ("," field)* | "opt:" field ("," field)*
dialect := "paged" | "legacy" | "mixed" | "none" | "load" |
"window" | "ref"
field is the literal query-key name as the router expects it, e.g. "ip", "mac", "KEYWORDS". A numeric field is suffixed with "#", which makes the generated Options struct use an int and render it without a decimal point. An empty string decodes to the zero value: the default paged dialect with no extra parameters.
It returns an error for an unknown dialect or a malformed clause, so a typo in v4_catalog.go fails the build instead of silently producing a query the router ignores.
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 SchemaPaths ¶ added in v1.2.0
func SchemaPaths() []string
SchemaPaths lists every endpoint path that carries a body contract, sorted, so a caller can enumerate the coverage.
func SetLogLevel ¶ added in v1.2.0
func SetLogLevel(l LogLevel)
SetLogLevel sets the floor for the SDK's own events. The global log backend still applies on top of this.
func StatusFor ¶ added in v1.2.0
StatusFor maps an iKuai error code to the HTTP status an oekit handler should answer with.
A status the router actually sent always wins. Failing that:
- the 4xxx band is the SDK's own validation band, so 400;
- a known iKuai code maps to its own meaning (401 auth, 403 permission, 400 bad payload);
- an SDK error with neither a code nor a router status means the SDK refused to send the request at all — options were missing, a page number was zero, an endpoint is not in the catalog. That is a client-side mistake, so it answers 400 rather than falling through to 500 and making an oekit handler blame its own server.
func TimeObjectGroup ¶ added in v1.2.0
TimeObjectGroup builds a group_value member for the time object group, which is a weekly schedule rather than a single value.
func UpdateFields ¶ added in v1.2.0
UpdateFields returns the update allowlist for an endpoint, or nil when the endpoint imposes none. It lets a caller inspect the contract before deciding how to build a payload.
func UpdatePayload ¶ added in v1.2.0
func UpdatePayload(ctx context.Context, c *Client, path string, id int64, updates map[string]any, keep []string) (map[string]any, error)
UpdatePayload prepares a body for a read-modify-write update: it fetches the current object, merges the updates over it, and drops the fields the firmware rejects on an update. This is what the iKuai web UI does, and several endpoints (DHCP services, VLAN, NAT rules, PPPoE) refuse a partial body rather than defaulting the missing fields.
The assembly order matches the firmware: caller updates win, then the create defaults fill what is still missing, then the update-only defaults do, then the endpoint's mirror rules run. Nothing overwrites a value the caller supplied, except a mirror rule explicitly marked Overwrite — the VLAN endpoint requires that, because its rule name and display name are the same field to the firmware.
keep lists the body fields the endpoint accepts. Pass nil to use the endpoint's recorded allowlist from V4Schemas; if the endpoint has no recorded allowlist, every field is kept.
func ValidateToken ¶
ValidateToken returns an error if the token is obviously malformed.
iKuai has shipped two token shapes and both authenticate:
- 32 lowercase hex characters, on older firmware.
- 32 base64 characters, which decode to a UUID prefix. This is what a current 4.x router issues — verified against hardware, where the token worked on every endpoint while failing this check.
The check is therefore deliberately a shape check rather than a format one. Rejecting a working token is far worse than accepting a malformed one: the router is the authority, and a bad token fails there with a clear error anyway. Call ValidateToken to catch a pasted-then-truncated string, not to pre-authenticate.
func WeekSchedule ¶ added in v1.2.0
WeekSchedule is the time-object schedule iKuai applies to most rules when no explicit window is given: every day, all day.
Types ¶
type APIError ¶
type APIError struct {
// BizError is the oekit error contract: a business code and an HTTP
// status code that an oekit handler can act on. For a router error it
// is derived from the iKuai code — see CodeFor and StatusFor.
*oekerrors.BizError
// Code is the iKuai error code, e.g. 3007 for an expired token.
Code int
// HTTPStatus is the status the router actually replied with.
HTTPStatus int
// Message is the router's message, with the SDK's hint appended when
// the code is recognized.
Message string
// Details carries per-field validation failures when the router
// supplies them.
Details []APIErrorDetail
// RetryAfter, when non-zero, carries a server-advised back-off hint
// (captured from the HTTP Retry-After header on 429 responses by
// httpjson.RetryAfterTransport; see RetryAfterTransport in retry.go).
RetryAfter time.Duration
// contains filtered or unexported fields
}
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 NewError ¶ added in v1.2.0
func NewError(msg string, opts ...ErrorOption) *APIError
NewError builds an APIError. Prefer this over a struct literal: it is the only path that fills in the oekit BizError the ecosystem expects.
func (*APIError) Biz ¶ added in v1.2.0
Biz returns the oekit business error for this failure, constructing it if the APIError was built as a literal.
func (*APIError) IsAuthFailure ¶ added in v1.2.0
IsAuthFailure reports whether the error means the token or session is missing, expired or invalid. Retrying with the same credentials will not help; the caller must refresh the token first.
func (*APIError) IsBadRequest ¶ added in v1.2.0
IsBadRequest reports whether the router rejected the request itself, which a caller can fix by correcting the payload.
func (*APIError) IsPermissionFailure ¶ added in v1.2.0
IsPermissionFailure reports whether the error means the account is authenticated but lacks permission for the operation. Retrying will not help; the caller needs a more privileged account.
func (*APIError) IsRetryable ¶ added in v1.1.0
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) and 5xx. Other 4xx are not retryable.
type APIErrorDetail ¶
type APIErrorDetail struct {
Field string `json:"field"`
Type string `json:"type"`
Msg string `json:"msg"`
}
APIErrorDetail is one field-level validation failure reported by the router.
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
// 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 ¶
Close releases the underlying transport and makes the client unusable.
It follows the oekit lifecycle contract: the ctx is accepted so a caller can bound the shutdown, the error is returned rather than swallowed, and repeated or concurrent calls are safe — a second Close returns the first one's result without doing the work again.
Close does not cancel in-flight requests; it closes idle connections so the process can exit promptly. To bound a request, pass a context with a deadline to the call itself.
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 assembles a query string from a map. It backs the Call escape hatch, which 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 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. See retry.go for the retryability rules and the back-off curve.
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 logx.Logger) ClientOption
WithStructuredLogger attaches a structured logger for this client only.
The default is the package-level Delegating logger (see logger.go), which follows whatever logx.SetDefault installed. Attaching a logger here narrows it to this client — useful in a library that serves several routers with different verbosity — without touching the global facade.
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 ErrorOption ¶ added in v1.2.0
type ErrorOption func(*APIError)
ErrorOption configures an APIError at construction time.
func WithCause ¶ added in v1.2.0
func WithCause(cause error) ErrorOption
WithCause attaches the underlying error, preserving it for errors.Is and errors.As on the cause.
func WithCode ¶ added in v1.2.0
func WithCode(code int) ErrorOption
WithCode sets the iKuai error code.
func WithDetails ¶ added in v1.2.0
func WithDetails(details []APIErrorDetail) ErrorOption
WithDetails attaches field-level validation failures.
func WithHTTPStatus ¶ added in v1.2.0
func WithHTTPStatus(status int) ErrorOption
WithHTTPStatus sets the status the router replied with.
func WithRetryAfter ¶ added in v1.2.0
func WithRetryAfter(d time.Duration) ErrorOption
WithRetryAfter records a server-advised back-off.
type LogLevel ¶
type LogLevel int
LogLevel selects the severity of an SDK event.
const ( // LogLevelDebug is per-request detail. LogLevelDebug LogLevel = iota // LogLevelInfo is lifecycle events such as retry scheduling. LogLevelInfo // LogLevelWarn is a recoverable condition, e.g. a retried request. LogLevelWarn // LogLevelError is an operation that failed. LogLevelError // LogLevelNone silences the SDK's own logging. LogLevelNone )
type Metrics ¶
type Metrics struct {
// contains filtered or unexported fields
}
Metrics is a small request counter for the client. It is deliberately not a Prometheus dependency: a library that forces a metrics backend on its consumers is a library nobody can embed in a script.
Record the numbers into whatever the host already runs:
stats, _ := client.Metrics().GetStats() promGauge.Set(float64(stats.RequestCount))
or attach the SDK to an oekit metrics facade from the host side instead.
func (*Metrics) GetStats ¶
GetStats returns the request count, the failure count and the mean latency observed so far.
func (*Metrics) RecordRequest ¶
RecordRequest notes one completed request.
type MirrorRule ¶ added in v1.2.0
type MirrorRule struct {
// From is the field to read.
From string
// To is the field to write.
To string
// Overwrite distinguishes the two firmware behaviours. When true the
// copy is unconditional — it replaces a value the caller just set,
// which is what the VLAN endpoint requires, since its display name and
// its rule name are the same field in the firmware's eyes. When false
// the copy only fills an empty To.
Overwrite bool
}
MirrorRule records that one body field is copied onto another after a read-modify-write update.
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 the transport failure may be retried. Pass the HTTP method to qualify network errors: a write is not retried, because it may already have reached the router.
func (*NetworkError) Unwrap ¶
func (e *NetworkError) Unwrap() error
type QueryDialect ¶ added in v1.2.0
type QueryDialect string
QueryDialect names the query-parameter contract an endpoint speaks. The iKuai v4 surface is not uniform: several dialects show up across the monitoring and auth groups, and picking the wrong one makes the router silently ignore the whole query string.
The dialects, as observed on device and cross-checked against the upstream CLI implementation:
DialectPaged — page/limit/filter/order/order_by (the default for most collections), optionally narrowed further by key/pattern. DialectLegacy — the uppercase dialect used by /monitoring/downstream, /monitoring/cameras and /monitoring/switch. It wants TYPE=data, LIMIT="<offset>,<count>", OFFSET, ORDER, ORDER_BY and KEYWORDS. There is no "page"; the caller computes the offset. DialectMixed — /auth/online-users takes lowercase page/limit but uppercase KEYWORDS/FINDS/ORDER/ORDER_BY. DialectNone — no paging at all; the endpoint returns everything. DialectLoad — the datetype/start_time/end_time/math window used by the monitoring load endpoints. DialectWindow — starttime/stoptime (no underscore) plus optional per-endpoint selectors such as ip/mac/appids.
const ( // DialectPaged is the default lowercase page/limit dialect. DialectPaged QueryDialect = "" // DialectLegacy is the uppercase TYPE/LIMIT/OFFSET dialect. DialectLegacy QueryDialect = "legacy" // DialectMixed is lowercase paging with uppercase sort/search keys. DialectMixed QueryDialect = "mixed" // DialectNone sends no paging parameters. DialectNone QueryDialect = "none" // DialectLoad is the datetype/start_time/end_time/math window. DialectLoad QueryDialect = "load" // DialectWindow is the starttime/stoptime window. DialectWindow QueryDialect = "window" // DialectRef is a reverse lookup: one required name parameter, no // paging. It answers "which rules reference this object group". DialectRef QueryDialect = "ref" )
type QueryField ¶ added in v1.2.0
type QueryField struct {
// Name is the key exactly as the router expects it, including case
// ("ip", "mac", "KEYWORDS", "FINDS", "TYPE").
Name string
// Required marks parameters the router rejects the call without.
Required bool
// Numeric marks parameters that must be rendered as an integer.
Numeric bool
}
QueryField describes one query parameter an endpoint accepts on top of its dialect's defaults.
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/limit/filter/order/order_by. The codegen emits a
// typed <Name>LoadOptions struct plus enum validation for these.
//
// Deprecated: prefer Query: "load". Load is still honoured and is
// treated as DialectLoad when Query is empty.
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
// Query is the compact per-endpoint query contract; see
// ParseQuerySpec. Empty means the standard paged dialect, which is
// what the generic List helpers already emit. Endpoints with a
// non-default contract additionally get a typed
// Query<Name>(ctx, *<Name>QueryOptions) helper.
//
// Query: "legacy+opt:status,device"
// Query: "paged+req:ip,mac+opt:limit#"
// Query: "window+req:appids+opt:starttime#,stoptime#"
Query 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)
func (V4Endpoint) QuerySpec ¶ added in v1.2.0
func (e V4Endpoint) QuerySpec() (QueryDialect, []QueryField, []QueryField, error)
QuerySpec decodes the endpoint's Query contract into its dialect and its extra required / optional parameters. An endpoint that still uses the deprecated Load flag decodes as DialectLoad.
type V4Schema ¶ added in v1.2.0
type V4Schema struct {
// CreateDefaults are the fields a create must carry when the caller
// supplies nothing. Caller-supplied values always win.
CreateDefaults map[string]any
// UpdateDefaults are filled in only on an update, not on a create.
//
// Some resources genuinely need a different default set per verb: the
// DHCP service endpoint writes no opt_type* fields on create, but an
// update must send twelve of them. A single CreateDefaults map cannot
// express that, which is why the two sets are separate.
UpdateDefaults map[string]any
// InputFields is the allowlist an update may send. Nil means the
// endpoint imposes no allowlist and every field is accepted.
InputFields []string
// RequiredFields are the fields a create must set explicitly; the SDK
// cannot invent them. Empty when every required field already has a
// meaningful default.
RequiredFields []string
// Mirror describes fields the firmware keeps in sync with one another.
Mirror []MirrorRule
// DropBlanks lists fields that must not be forwarded as an empty string
// when they come back from the router. The firmware reads an empty
// option value as "no option configured" rather than "unchanged", so
// the field is removed from the update body and the endpoint's default
// fills it instead. A value the caller supplies is left alone — the
// caller means it.
DropBlanks []string
// DropSuffix lists field-name suffixes the router derives for its own
// use and rejects on write. The routing endpoints return a "_int"
// companion for several fields; sending one back fails the update.
DropSuffix []string
// NormalizeSelectors rewrites an empty selector pair from a JSON object
// into an empty array before the body goes out. Some firmware reads
// back {"custom":{},"object":{}} where it wrote arrays, and rejects the
// object form on the next write.
NormalizeSelectors bool
}
V4Schema is the body contract for one endpoint path.
func (V4Schema) AllowsField ¶ added in v1.2.0
AllowsField reports whether an update to this endpoint may carry field. An endpoint without an allowlist accepts everything.
func (V4Schema) HasDefaults ¶ added in v1.2.0
HasDefaults reports whether the endpoint carries create defaults.
func (V4Schema) HasInputFields ¶ added in v1.2.0
HasInputFields reports whether the endpoint constrains update fields.
func (V4Schema) HasUpdateDefaults ¶ added in v1.2.0
HasUpdateDefaults reports whether the endpoint fills extra fields on an update that a create does not carry.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
codegen generates the v4 service layer from v4_catalog.go.
|
codegen generates the v4 service layer from v4_catalog.go. |
|
Example program demonstrating the v4 SDK.
|
Example program demonstrating the v4 SDK. |
|
Package output renders iKuai API responses for humans and for machines.
|
Package output renders iKuai API responses for humans and for machines. |
|
Package session persists the router address and API token so an application does not have to hard-code them.
|
Package session persists the router address and API token so an application does not have to hard-code them. |