ikuaiapi

package module
v1.3.4 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: MIT Imports: 20 Imported by: 2

README

ikuai-api

Go Report Card GoDoc License

A Go SDK for the iKuai v4.0 REST API — the local management API served by routers running iKuai OS 4.x. v3's /Action/call protocol is not supported.

The distinguishing thing about this SDK is that it does not treat the v4 API as uniform, because it isn't. The page-size parameter, the sort keys, the query dialect and the response envelope all differ between groups of endpoints, and getting any of them wrong makes the router silently ignore you rather than fail. Those contracts are recorded in v4_catalog.go and v4_schemas.go and turned into typed helpers, so callers write QueryMonitoringDownstream(ctx, opts) instead of hand-assembling a query string that quietly does nothing.

Contents

Install

go get github.com/zy84338719/ikuai-api

Requires Go 1.24+. The only dependencies are github.com/oekit/logx and github.com/oekit/pkg — make zero-dep fails the build if a third-party require ever appears.

Quick start

package main

import (
    "context"
    "encoding/json"
    "fmt"
    "log"
    "time"

    ikuaiapi "github.com/zy84338719/ikuai-api"
    "github.com/zy84338719/ikuai-api/service"
)

func main() {
    client, err := ikuaiapi.NewClient("https://192.168.1.1",
        ikuaiapi.WithToken(token),
        ikuaiapi.WithTimeout(15*time.Second),
    )
    if err != nil {
        log.Fatal(err)
    }
    // Close takes a context, returns an error, and is safe to call twice.
    defer func() { _ = client.Close(context.Background()) }()

    api := service.NewAPIClient(client)
    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()

    raw, err := api.Monitoring().GetMonitoringSystem(ctx)
    if err != nil {
        log.Fatal(err)
    }
    var overview map[string]any
    if err := json.Unmarshal(raw, &overview); err != nil {
        log.Fatal(err)
    }
    fmt.Printf("hostname: %v  uptime: %v\n", overview["hostname"], overview["uptime"])
}
Getting a token

iKuai v4 authenticates with a Bearer token, generated in the router web UI: System → Auth → API Token.

Two token shapes exist in the field, and both work:

Shape Looks like Seen on
hex 32 characters, 0-9a-f older firmware
base64 32 characters, decodes to a UUID prefix current 4.x firmware

A base64 token authenticates fine on every endpoint — it just fails a hex-shaped validator, which is why ValidateToken accepts both rather than rejecting tokens that work. It is a shape check to catch a truncated paste, not a pre-authentication: the router is the authority.

if err := ikuaiapi.ValidateToken(token); err != nil {
    return fmt.Errorf("token looks wrong: %w", err)
}

Three contracts to know before you write anything

Each of these was found the hard way, and each one fails silently.

1. The page-size parameter is limit

page_size is accepted by the router and ignored — you get every row back. Against a collection of nine online clients:

query rows returned
limit=1 / 3 / 5 1 / 3 / 5
page_size=1 / 3 / 5 9 / 9 / 9

Page 2 with limit=3 returns a different slice; the same page requested with page_size repeats page 1 exactly.

The generated List<Name> helpers send limit.

2. Sort keys are order = direction, order_by = field

Everywhere, including the security and advanced-service collections. Swapping the two returns no rows at all, on a table that plainly has data. Order always means the direction and OrderBy always means the field, on every endpoint.

3. Collections speak seven different query dialects

Sending the wrong shape is silently ignored, exactly like page_size.

Dialect Endpoints Query
paged most collections page, limit, filter, order, order_by
legacy /monitoring/downstream, /monitoring/cameras, /monitoring/switch TYPE=data, LIMIT="<offset>,<count>", OFFSET, ORDER, ORDER_BY
mixed /auth/online-users page, limit + KEYWORDS, FINDS, ORDER, ORDER_BY
window /monitoring/protocols*, /monitoring/clients/protocols*, /log/url-visits starttime, stoptime (no underscore)
none /monitoring/ssid-clients, channel-clients, wireless-traffic, clients-traffic-load only the endpoint's own selectors
load /monitoring/cpu, memory, disk, cputemp, terminals, connections, network datetype, start_time, end_time, math (underscored)
ref /…-objects/ref group_name, no paging

29 endpoints carry a recorded dialect; the rest use the default. For the non-default ones the generator emits a Query<Name> helper that builds the right shape and rejects an incomplete request before it leaves the process:

// legacy dialect: LIMIT is "<offset>,<count>", there is no "page"
raw, err := api.Monitoring().QueryMonitoringDownstream(ctx,
    &service.MonitoringDownstreamQueryOptions{
        Page: 1, PageSize: 20,
        Order: "desc", OrderBy: "id",
        Status: "1", Device: "camera",
    })

// window dialect: ip and mac are required
raw, err = api.Monitoring().QueryMonitoringClientsProtocols(ctx,
    &service.MonitoringClientsProtocolsQueryOptions{
        IP: "192.168.1.100", MAC: "08:9b:4b:01:7e:7c",
        StartTime: 1773300000, StopTime: 1773303600,
    })

Inspect any endpoint's contract at runtime:

for _, ep := range service.Endpoints() {
    dialect, required, optional, err := ep.QuerySpec()
    // ...
}

Reading

// plain collection: page/limit/filter/order/order_by
raw, err := api.Network().ListNetworkDhcpServices(ctx,
    &service.NetworkDhcpServicesListOptions{
        Page: 1, PageSize: 50,
        Filter: "enabled==yes",
        Order: "desc", OrderBy: "id",
    })

// no parameters at all
raw, err = api.Monitoring().GetMonitoringSystem(ctx)

// load window over a time bucket
raw, err = api.Monitoring().LoadCpu(ctx, &service.MonitoringCpuLoadOptions{
    DataType: "hour", // hour | day | week | month
    StartTime: time.Now().Add(-time.Hour).Unix(),
    EndTime:   time.Now().Unix(),
    Math:      "avg", // avg | max
})
Two-level resources

WireGuard peers live under a tunnel, so both identifiers are path parameters:

api.Vpn().ListVpnWireguardPeers(ctx, opts)
api.Vpn().GetVpnWireguardPeer(ctx, tunnelID, peerID)
api.Vpn().CreateVpnWireguardPeers(ctx, tunnelID, body)
api.Vpn().DeleteVpnWireguardPeer(ctx, tunnelID, peerID)

An endpoint whose path ends in a placeholder gets no List — there is no collection at that path.

Writing

The firmware validates writes strictly, and for most rule-like resources a partial update is rejected rather than completed with the router's own defaults — which would silently reconfigure whatever you left out. 73 endpoints record their create defaults, update allowlist and required fields; the helpers apply them.

// create: defaults filled in, required fields checked locally
body, err := ikuaiapi.CreateBody("/security/acl-rules", map[string]any{
    "tagname":  "block_ssh",
    "action":   "drop",
    "protocol": "tcp",
    "dst_port": ikuaiapi.AddressValues("22"),
})
// enabled=yes prio=50 dir=forward, untouched selectors are the empty pair,
// time is the all-day window — and a missing required field is reported
// here rather than surfacing later as an opaque 3001.
rowid, err := api.Security().CreateSecurityAclRules(ctx, body)

// update: read-modify-write with the endpoint's own allowlist
updated, err := ikuaiapi.UpdatePayload(ctx, client, "/network/nat/rules", id,
    map[string]any{"nat_addr": "203.0.113.5"}, nil) // nil = use the schema's list
Body conventions the firmware insists on
Convention Helper
enabled is the string "yes" / "no", never a JSON boolean Enabled(true)
address/port/protocol selectors are {"custom":[…],"object":[]}, not an array AddressValues("80,443")
object-group members live in group_value, one single-key object each ObjectGroup("ip", "10.0.0.1")
the time group holds schedules instead of values TimeObjectGroup(...), WeekSchedule()
only an allowlisted set of fields may be JSON numbers CoerceBody(body)

That last one is the subtle one. Most numeric-looking fields must stay strings, or an SNMP community of "161" or a VLAN name of "0010" gets mangled. IsIntegerAPIField and IntegerAPIFields expose the classification.

Three firmware behaviours are reproduced rather than smoothed over, because normalizing them breaks the write — see skills/writing.md for the full list.

Response envelopes

Three wrapping shapes come back, and confusing them is easy:

Shape Example Where
data {"data":[…],"total":n} most collections
results {"results":[…]} monitoring load endpoints
group paging {"ip_data":[],"ip_total":0} object groups, DHCP static

The third is the trap: /ip-objects answers with ip_data, /ip6-objects with ipv6_data, and the members are not at the top level. Read the array and the counter separately:

var page struct {
    IPData  []map[string]any `json:"ip_data"`
    IPTotal int              `json:"ip_total"`
}
json.Unmarshal(raw, &page)

FirstObject unwraps all three, and a read-modify-write update goes through it. An empty group correctly reports "no object" rather than handing back the wrapper with its counters as if they were a row.

The client also normalizes the bare nil tokens some firmware emits in place of null before parsing, and Create methods return the rowid the router reports on success.

Errors

Router-side failures come back as *ikuaiapi.APIError, which embeds an oekit BizError. The iKuai code becomes the business code, and an oekit handler's mw.Fail reads a status without any adapter:

iKuai code Meaning BizCode HTTPCode Predicate
3001 parameter error 3001 400 IsBadRequest()
3007 token expired/invalid 3007 401 IsAuthFailure()
1008 session expired 1008 401 IsAuthFailure()
10014 permission denied 10014 403 IsPermissionFailure()
4xxx SDK-local validation 4900 400 —

The last row is a deliberate split: a 4xxx code means the request was never sent. An SDK-local failure — missing options, a page number of zero, an endpoint absent from the catalog — answers 400 rather than falling through to 500, so a service does not blame its own server for a caller's mistake.

_, err := api.Network().GetNetworkDnsConfig(ctx)

var apiErr *ikuaiapi.APIError
switch {
case errors.As(err, &apiErr):
    fmt.Printf("code=%d status=%d msg=%q\n",
        apiErr.Code, apiErr.Biz().HTTPCode, apiErr.Message)
    fmt.Println("try:", apiErr.Remedy())
}

*ikuaiapi.NetworkError wraps transport failures (DNS, refused, TLS, timeout) and also carries the original error for errors.Is.

Both types implement IsRetryable() bool. The SDK retries transient failures with exponential back-off and honours Retry-After. Its jitter is one-sided — a retry never fires earlier than its exponential baseline, so back-off cannot collapse into a retry storm against a struggling router. A write is never auto-retried on a transport error, because that request may already have reached the device.

Logging and metrics

Logging goes through the oekit logx facade with a lazily resolved package logger, so the SDK never picks a backend or a service name on your behalf. Install one in main and everything follows:

logx.UseSlog("my-service") // structured JSON
ikuaiapi.SetLogLevel(ikuaiapi.LogLevelInfo)

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, redact by key before installing:

logx.SetDefault(logx.WithFilter(logx.UseSlog("svc"),
    logx.FilterKey("url"), logx.FilterKey("path")))

WithStructuredLogger(logx.Logger) narrows the logger for one client without touching the global facade.

For counters, Metrics collects request count, failure count and mean latency without forcing a metrics backend on you:

metrics := ikuaiapi.NewMetrics()
client, _ := ikuaiapi.NewClient(base, ikuaiapi.WithToken(t), ikuaiapi.WithMetrics(metrics))
// later
count, errs, avg := metrics.GetStats()

Credentials

Rather than hard-coding an address and a token, resolve them:

client, resolved, err := session.ResolveClient()
fmt.Println("credentials came from:", resolved.Source()) // session | env | none

Resolution is session file → environment → unset, and the source is reported rather than guessed. The session file is written with 0600 permissions and replaced atomically; environment values stay in memory and are never persisted.

export IKUAI_API_BASE_URL=https://192.168.1.1   # or IKUAI_CLI_BASE_URL
export IKUAI_API_TOKEN=<token>                  # or IKUAI_CLI_TOKEN

NormalizeBaseURL canonicalizes an address — upgrading a bare host to https, stripping any path — because the v4 API lives at a fixed prefix and a stray path silently breaks every call.

Rendering

output turns a response into something readable or pipeable:

r := output.New(os.Stdout, output.FormatAuto) // table on a TTY, JSON when piped
r = r.WithOptions(output.RenderOptions{
    HumanTime: true,
    Columns:   []string{"ip_addr", "mac", "upload", "download"},
})
err := r.Value(decoded)

It flattens the firmware's own structures — the {"custom":[…],"object":[…]} selector pair and group_value members render as lines rather than opaque JSON — converts timestamp fields to local time, converts headers to UPPER_SNAKE_CASE, and drops whole trailing columns rather than truncating a value in a narrow terminal.

Service groups

Group Covers Endpoints
advanced FTP, HTTP, Samba, SNMPD 6
auth accounts, packages, web portal, online sessions 4
interfaces LAN, WAN, WAN-VLAN, physical NICs 4
log system, arp, auth, dhcp, pppoe, web, ddns, notice, wireless, url-visits 10
monitoring system, cpu/memory/disk/…, clients, traffic, protocols, wireless 37
network dhcp, dhcpv6, vlan, nat/dnat/dmz, dns, qos, pppoe, ac 25
objects 7 object groups + 7 reverse-lookup endpoints 14
routing static routes, stream shunting (domain / 5-tuple / l7 / load-balance / updown) 6
security acl, mac, l7, url rules, domain blacklist, peerconn, terminals, advanced 13
system basic, ntp, alg, kernel, cpufreq, disks, files, backup, upgrade, web-admin, … 24
vpn pptp / l2tp / openvpn / ikev2 servers and clients, ipsec, wireguard + peers 12
wireless blacklist, VLAN rules 2

Reach any group with api.<Group>():

api.Network().ListNetworkDhcpServices(ctx, opts)
api.System().GetSystemBasicConfig(ctx)
api.Monitoring().QueryMonitoringClientsOnline(ctx, opts)

Options

client, err := ikuaiapi.NewClient("https://192.168.1.1",
    ikuaiapi.WithToken(token),                  // Bearer token
    ikuaiapi.WithTimeout(15*time.Second),       // per-request timeout
    ikuaiapi.WithInsecureSkipVerify(true),      // trust the router's self-signed cert
    ikuaiapi.WithHTTPClient(custom),            // bring your own *http.Client
    ikuaiapi.WithAPIBase("/api/v4.0"),          // override the path prefix
    ikuaiapi.WithRawMode(true),                 // return the full envelope
    ikuaiapi.WithDryRun(true),                  // preview requests, send nothing
    ikuaiapi.WithRetry(3),                      // total attempt count
    ikuaiapi.WithRetryDelay(200*time.Millisecond, 5*time.Second),
    ikuaiapi.WithMetrics(ikuaiapi.NewMetrics()),
    ikuaiapi.WithStructuredLogger(logx.NewStdLogger("poller", logx.LevelInfo)),
)

WithDryRun is the safe way to see what a call would do: it returns the request as JSON and contacts nothing. Use it before any destructive write.

Generated API shapes

The generator emits one of these per catalog entry:

  1. Parameterless GET — Get<Name>(ctx)
  2. Query helper — Query<Name>(ctx, *<Name>QueryOptions) for endpoints whose dialect is not the default
  3. CRUD — List<Name> / Get<Name> / Create<Name> / Update<Name> / Patch<Name> / Delete<Name>, where Create returns the rowid

Each carries its path and verbs in a doc comment above it:

// ListNetworkDhcpServices lists items at /network/dhcp/services.
//
// Methods: GET, POST, PUT, PATCH

If a generated helper does not exist yet, Call is the escape hatch: it resolves the (group, name) pair from the catalog and dispatches the request with the method, body and query params you supply.

raw, err := api.Call(ctx, "interfaces", "wan-config", "GET", nil, nil)

Call resolves static catalog paths, so it cannot address a sub-resource — use the generated helpers for those.

Development

make test        # go test ./...
make check       # fmt + vet + test + dependency gate
make race        # go test -race ./...
make generate    # regenerate service/ from the contract tables
make zero-dep    # only github.com/oekit/* may appear in the module graph
make example     # runnable demo, honours IKUAI_DRY_RUN=1

The service/ package is generated. To change what the SDK exposes, edit v4_catalog.go (paths, verbs, query dialect, sort behaviour) or v4_schemas.go (body defaults, allowlists, required fields), then run make generate. CI fails if regeneration produces a diff.

Project layout

.
├── doc.go                 — package documentation
├── client.go              — HTTP, retry/back-off, envelope, sanitization
├── errors.go              — APIError (oekit BizError), NetworkError, sentinels
├── fields.go              — write-body conventions and read-modify-write
├── auth.go                — token shape validation
├── logger.go              — logx.Delegating package logger, level floor
├── metrics.go             — request counters and latency
├── version.go             — SDKVersion, Version enum
├── v4_catalog.go          — 157 endpoints + query dialect contracts
├── v4_schemas.go          — 73 endpoint body contracts
├── codegen/               — service-layer generator
├── service/               — generated, one file per group + root.go
├── session/               — credential persistence and resolution
├── output/                — table / JSON rendering
├── skills/                — agent-facing guides
├── example/               — runnable demo
├── AGENTS.md              — hard rules for humans and agents
└── llms.txt               — machine-readable entry point

Verification status

Endpoints, query dialects and body contracts were checked against a live iKuai OS 4.x router, and several entries exist because a probe proved the obvious spelling wrong:

  • 157 endpoints; 29 carry a query-dialect contract, 73 a body contract.
  • 147 of 155 GET-addressable endpoints answer 200. The other eight are five POST-only action endpoints, the two IKEv2 endpoints (the feature is absent on that firmware), and /vpn/wireguard (disabled there).
  • All 11 action endpoints answer {"message":"Success"} under POST.
  • Write path verified end to end on an object group: create, read back, update, read back, delete — the group_value encoding round-trips byte-for-byte, including non-ASCII comments.
  • Every allowlist was cross-checked field by field against live responses. Fields the router returns and accepts on write were added; hardware readouts and computed counters stay out deliberately, and v4_schemas.go records which is which.

Two things could not be settled on that device: the legacy uppercase dialect and the /auth/online-users mixed dialect, because downstream, cameras and switch are empty there and both spellings return an empty result. They are encoded from the upstream client and flagged as unverified.

Known limitations

  • The legacy and mixed dialects are encoded from an independent implementation, not confirmed on hardware — see above.
  • /vpn/ikev2/services 404s on the firmware tested; that is the feature being absent, not the path being wrong.
  • There is no concurrency helper. Client is safe for concurrent use, and the generated methods take a context, but the SDK deliberately does not start goroutines on your behalf.
  • Metrics is a small in-process counter, not a Prometheus integration. Feed the numbers into whatever your service already runs.

License

MIT. See LICENSE.

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

View Source
const SDKVersion = "1.3.3"

SDKVersion is the semantic version of this SDK.

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

View Source
const TokenLength = 32

TokenLength is the character length of an iKuai API token, in both of the shapes firmware has shipped.

View Source
const V4APIBase = "/api/v4.0"

V4APIBase is the canonical root for all iKuai v4 REST endpoints.

Variables

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

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

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

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

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

func AddressValues(values ...string) map[string]any

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

func AsBizError(err error) (*oekerrors.BizError, bool)

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

func CodeFor(ikuaiCode int) int

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

func CoerceBody(body map[string]any) map[string]any

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

func CreateBody(path string, overrides map[string]any) (map[string]any, error)

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

func Enabled(v bool) string

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

func IntegerAPIFields() map[string]bool

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

func IsIntegerAPIField(name string) bool

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

func MergeBody(existing, updates map[string]any) map[string]any

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

func ObjectGroup(group string, values ...string) ([]any, error)

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

func ParseEnabled(s string) (bool, error)

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

func SanitizeNil(body []byte) []byte

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

func StatusFor(ikuaiCode, routerStatus int) int

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

func TimeObjectGroup(scheduleType, weekdays, startTime, endTime, comment string) map[string]any

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

func UpdateFields(path string) []string

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

func ValidateToken(token string) error

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

func WeekSchedule() map[string]any

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

func (e *APIError) Biz() *oekerrors.BizError

Biz returns the oekit business error for this failure, constructing it if the APIError was built as a literal.

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) IsAuthFailure added in v1.2.0

func (e *APIError) IsAuthFailure() bool

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

func (e *APIError) IsBadRequest() bool

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

func (e *APIError) IsPermissionFailure() bool

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

func (e *APIError) 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) and 5xx. Other 4xx are not retryable.

func (*APIError) Remedy added in v1.2.0

func (e *APIError) Remedy() string

Remedy returns the actionable fix for a known iKuai error code, or an empty string when the code is not recognized.

func (*APIError) Unwrap added in v1.2.0

func (e *APIError) Unwrap() error

Unwrap exposes the embedded BizError so that errors.As can reach it. An oekit handler unwrapping the error therefore still sees the business code and HTTP status, and a caller can keep reaching the cause.

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

func (c *Client) Close(ctx context.Context) error

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

func (c *Client) Delete(ctx context.Context, p string, body any) (json.RawMessage, error)

Delete issues a DELETE request. The optional body is sent as JSON.

func (*Client) Do

func (c *Client) Do(ctx context.Context, method, p string, body, out any) error

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

func (c *Client) FormatQuery(q map[string]string) string

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

func (c *Client) Metrics() *Metrics

Metrics returns the attached Metrics collector, or nil if none was set.

func (*Client) Patch

func (c *Client) Patch(ctx context.Context, p string, body any) (json.RawMessage, error)

Patch issues a PATCH request with a JSON body.

func (*Client) Post

func (c *Client) Post(ctx context.Context, p string, body any) (json.RawMessage, error)

Post issues a POST request with a JSON body.

func (*Client) Put

func (c *Client) Put(ctx context.Context, p string, body any) (json.RawMessage, error)

Put issues a PUT request with a JSON body.

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
)

func (LogLevel) String added in v1.2.0

func (l LogLevel) String() string

String renders the level name.

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 NewMetrics

func NewMetrics() *Metrics

NewMetrics returns an empty collector.

func (*Metrics) GetStats

func (m *Metrics) GetStats() (count int64, errors int64, avgDuration time.Duration)

GetStats returns the request count, the failure count and the mean latency observed so far.

func (*Metrics) RecordRequest

func (m *Metrics) RecordRequest(duration time.Duration, hasError bool)

RecordRequest notes one completed request.

func (*Metrics) Reset

func (m *Metrics) Reset()

Reset clears the collected statistics.

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

type NetworkError struct {
	Message string
	Cause   error
}

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 Schema added in v1.2.0

func Schema(path string) (V4Schema, bool)

Schema returns the body contract for an endpoint path.

func (V4Schema) AllowsField added in v1.2.0

func (s V4Schema) AllowsField(field string) bool

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

func (s V4Schema) HasDefaults() bool

HasDefaults reports whether the endpoint carries create defaults.

func (V4Schema) HasInputFields added in v1.2.0

func (s V4Schema) HasInputFields() bool

HasInputFields reports whether the endpoint constrains update fields.

func (V4Schema) HasUpdateDefaults added in v1.2.0

func (s V4Schema) HasUpdateDefaults() bool

HasUpdateDefaults reports whether the endpoint fills extra fields on an update that a create does not carry.

type Version

type Version int

Version enumerates the iKuai API generations the SDK recognises.

const (
	// VersionUnknown is the zero value; iKuai API v4 is the only supported
	// version, so new clients should pass VersionV4 explicitly.
	VersionUnknown Version = iota
	// VersionV4 is the current iKuai REST API (/api/v4.0).
	VersionV4
)

func (Version) String

func (v Version) String() string

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.

Jump to

Keyboard shortcuts

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