AI Card Bao DASH.AICARDBAO.COM
Home / 开源 / 9router-go
AI TOOL / #12829

9router-go

A high-performance LLM proxy gateway written in Go, providing unified management of model access and routing for coding tools such as Claude Code, Codex, and Cursor.

Introduction

FREE AI Router & Token Saver with Single Binary

Never stop coding. Save 20-40% tokens with RTK + auto-fallback to FREE & cheap AI models.

Connect Claude Code, Cursor, Antigravity, Codex, Gemini, OpenCode, Cline, OpenClaw... to 150+ AI providers & 1000+ models — no Node.js needed at runtime.

🚀 Quick Start • 💡 Features • ⚙️ Setup • 🔄 Share DB with 9Router • 🌐 Upstream


🤔 Why 9router-go?

Same idea as 9Router, minus the Node.js runtime: one Go binary serves the proxy APIs + an embedded Svelte dashboard.

Stop wasting money, tokens and hitting limits:

  • ❌ Subscription quota expires unused every month
  • ❌ Rate limits stop you mid-coding
  • ❌ Tool outputs (git diff, grep, ls...) burn tokens fast
  • ❌ Manual switching between providers

9router-go solves this:

  • ✅ RTK Token Saver — auto-compress tool_result content, save 20-40% tokens
  • ✅ Auto fallback — Subscription → Cheap → Free, zero downtime
  • ✅ Extended combo routing — per-combo strategy: fallback, round-robin, sticky, capacity, or fusion
  • ✅ Multi-account — round-robin between accounts per provider
  • ✅ Proxy per API key — bind a proxy pool to each provider API key (connection), one-by-one or via Apply Proxy across many at once
  • ✅ Custom headers — add your own request headers to custom compatible providers
  • ✅ Unified custom provider add — one shared dialog adds OpenAI-/Anthropic-compatible endpoints
  • ✅ Custom usage ranges — analyze any window (14d, 12h), not just fixed presets
  • ✅ Extended logging — live console log with level filters & search, plus per-request payload inspector
  • ✅ Single binary — Go + embedded dashboard, works with Claude Code, Codex, Cursor, Cline, any CLI tool

🔄 How It Works

┌─────────────┐
│  Your CLI   │  (Claude Code, Codex, OpenClaw, Cursor, Cline...)
│   Tool      │
└──────┬──────┘
       │ http://localhost:20130/v1
       ↓
┌─────────────────────────────────────────────┐
│         9router-go (Smart Router)           │
│  • RTK Token Saver (cut tool_result tokens) │
│  • Format translation (OpenAI ↔ Claude)     │
│  • Quota tracking                           │
│  • Auto token refresh                       │
└──────┬──────────────────────────────────────┘
       │
       ├─→ [Tier 1: SUBSCRIPTION] Claude Code, Codex, GitHub Copilot
       │   ↓ quota exhausted
       ├─→ [Tier 2: CHEAP] GLM ($0.6/1M), MiniMax ($0.2/1M)
       │   ↓ budget limit
       └─→ [Tier 3: FREE] Kiro, OpenCode Free, Vertex ($300 credits)

Result: Never stop coding, minimal cost + 20-40% token savings via RTK

⚡ Quick Start

1. Install (one line):

# macOS / Linux
curl -fsSL https://raw.githubusercontent.com/luqman-v1/9router-go/main/install.sh | bash
# Windows (PowerShell — installer writes to %LOCALAPPDATA% + user PATH, no admin needed)
irm https://raw.githubusercontent.com/luqman-v1/9router-go/main/install.ps1 | iex
CPU without AVX? Celeron/Pentium N-series, older Atom and some VMs max out at SSE4.2, and an x86-64 binary built for a newer microarchitecture dies with Illegal instruction before it starts. Use the no-AVX asset (linux/amd64) instead of the default one: ``bash curl -fsSL https://raw.githubusercontent.com/luqman-v1/9router-go/main/install-noavx.sh | bash ` It installs the same binary from the 9router-go-linux-amd64-noavx release asset, which is built with CGO_ENABLED=0 and GOAMD64=v1. VARIANT=noavx on install.sh` does the same thing.

🎉 Then start it (defaults: port 20130, data ~/.9router — no flags needed):

9router-go
# Dashboard: http://localhost:20130 (Default password: 123456)
Already using upstream 9Router? Point 9router-go at the same data dir — it opens the same DATA_DIR/db/data.sqlite. Your providers, connections, combos, API keys, and usage history carry over as-is. No import step, no migration. See Sharing a database with 9Router for the caveats.

Keep the terminal free (background mode):

9router-go start          # same as: 9router-go --background   (or -d)
9router-go status         # is it running? (pid, dashboard, log)
9router-go restart        # replace the running daemon
9router-go logs -n 100    # tail the background log
9router-go doctor         # why is it not reachable? port, pid, data dir, db
9router-go stop           # stop it

doctor is the diagnostic for a gateway that will not answer. status tells you whether a daemon is alive; doctor tells you *why* it is not, checking the resolved port, the pid claim, whether the listening socket belongs to the gateway or a foreign process, the data directory's writability, the database file, and a failed-bind marker in the run log. Each failing line names the platform command that fixes it (netstat/taskkill on Windows, lsof/kill elsewhere). --port diagnoses an address other than the one PORT resolves.

The detached process records itself in DATA_DIR/run/gateway.pid and writes its output to DATA_DIR/run/gateway.log. A second start while one is running refuses instead of fighting over the port, and a daemon killed from Task Manager leaves nothing behind: the stale pid file is cleaned on the next command.

Windows stops the process with TerminateProcess instead of SIGTERM, so stopping skips the graceful drain; use the dashboard's Shutdown button or 9router-go restart when you want in-flight streams to finish first.

Start on boot (autostart):

9router-go service install     # systemd user unit, launchd agent, OpenRC/runit service, cron @reboot, or a Windows logon task
9router-go service status      # which backend owns the entry, and whether it is enabled/active
9router-go service start       # start the supervised service now (falls back to the background daemon)
9router-go service restart     # restart it
9router-go service stop        # stop it now but keep it enabled for boot
9router-go service uninstall   # remove the autostart entry

install picks the native backend for the host. systemd, launchd, and cron all install into the user scope and need no root; runit's ~/service path too. Two exceptions: OpenRC is a system service and needs root (service install refuses without it — run with sudo, or pick --backend cron), and Windows has two backends: windows-run (a HKCU\...\Run registry entry, installed from a non-elevated session with no admin rights) and windows-task (a schtasks scheduled task, which requires an Administrator console). A non-elevated session gets windows-run directly; an elevated one tries windows-task first and falls back to windows-run if schtasks fails. Both run as the current user at logon, so they read that user's data dir rather than SYSTEM's. Force a backend with --backend systemd|launchd|openrc|runit|cron|windows-run|windows-task.

2. Connect a FREE provider (no signup needed):

Dashboard → Providers → Connect Kiro AI (~50 credits/month free) or OpenCode Free (no auth) → Done!

3. Use in your CLI tool:

Claude Code / Codex / OpenClaw / Cursor / Cline Settings:
  Endpoint: http://localhost:20130/v1
  API Key:  [Settings → API Keys in the dashboard]
  Model:    kr/claude-sonnet-4.5

That's it! Start coding with FREE AI models.

Alternatives:

# Docker — no build needed
docker run -d --name 9router-go --restart unless-stopped \
  -p 20130:20130 -v "$HOME/.9router:/data" \
  -e PORT=20130 -e DATA_DIR=/data \
  -e INITIAL_PASSWORD=your-secure-password \
  luqmenul/9router-go:latest

# Manual download — pick your file, no command line guesswork:
# Windows → .exe | Mac M1+ → darwin-arm64 | Mac Intel → darwin-amd64
# Linux VPS → linux-amd64 | Raspberry Pi → linux-arm64

📦 All release binaries • 🔨 Build from source


💡 Key Features

  • 🖥️ Native Svelte 5 dashboard: providers, OAuth, combos, proxy pools, API keys, usage, quota, settings, plans, per-entry sidebar visibility
  • 💱 Cost display in USD, IDR, EUR and ten more currencies — editable rate table, dual display, one-click refresh from a public provider
  • 🔌 OpenAI Chat, Claude Messages, Gemini, Ollama-compatible, Responses, embeddings, media, search, web tools, rerank
  • 🔁 Combos with fallback, round-robin, sticky routing, fusion, capability-aware reordering
  • 👥 Per-provider executors, OAuth refresh, reactive 401 retry
  • 📡 Live usage + console-log SSE streams, stall detection
  • 🩺 Per-model circuit breakers: a model that keeps failing sits out its cooldown while the rest of its provider keeps serving — a provider outage never parks the whole model list, and one throttled account never parks a model the others serve fine. See the Model Breakers page, or Advanced Features
  • 💾 SQLite WAL persistence, outbound proxy support, self-update, MITM commands, Docker, cross-compilation
  • 💰 Per-key budget enforcement (USD + tokens, four periods, hard cutoff) and /api/usage/export — from new-api
  • 🧪 Dashboard Playground: a streaming, multi-turn conversation through the engine's own dispatch, with no engine key — attributed to a picked key, budget and allowlist enforced, nothing persisted (inspired by new-api)
  • 📡 Uptime heartbeat (Push-Monitor / Uptime Kuma) — from new-api
  • 🔀 Vertex v1beta1 per-connection switch, and an optional HTTP/2 PING health check for idle upstream connections — from new-api
  • 🚦 Rate ceilings per key — RPM/TPM/RPH/RPD/concurrency with a FIFO queue — plus a per-client-IP gate checked before every key window, so a caller holding or minting many keys cannot escape the host ceiling
  • 🧭 Connection strategies: failover, round-robin, sticky and least-busy (the key with the fewest turns in flight goes next), plus per-custom-provider capacity limits — RPM/TPM/concurrency, a FIFO queue timeout, a lifetime token quota and a contract expiry — and a sparse per-model capability override that leaves an untouched field on detection
  • 📅 Usage periods from one hour to sixty days and month-to-date, with the Claude and Codex seat tier and its lapse date in the quota tracker
  • ⏱️ Optional end-to-end request timeout (totalRequestTimeoutMs, off by default) to reclaim a hung upstream without cutting a slow reasoning stream

For sequential combo routing, set Model response timeout in seconds (decimals such as 5.3 are fine) in the combo's Edit dialog, or from the compact field on the combo card. Empty or 0 disables it. The timer covers each model candidate except the last, including connection selection and waiting for a usable response. If it expires before output is committed, the router cancels that candidate and tries the next. The last candidate keeps the gateway's normal deadline, so the setting never makes a combo fail sooner than it would without it (#744). An active stream is not cut off by this setting. For non-streaming requests, the timer covers the wait for the complete response. Fusion panel timing is separate. A model that times out is left out of that combo for a grace period (default 5 minutes, set per combo under the timeout in the Edit dialog; 0 re-includes it on the next request) and then rejoins the chain. If every model in the chain is inside its grace period, the full chain is used. The pause is held in memory and resets on restart. Stored as firstTokenGraceMs next to the timeout. The dashboard shows seconds; the setting is stored in milliseconds as comboStrategies[comboName].firstTokenTimeoutMs.


🔄 Sharing a database with 9Router

Already running 9Router (the Next.js version)? 9router-go reads that exact database. There is no import, no export, and no migration step.

Both projects default to the same file and speak the same schema:

Path
macOS / Linux~/.9router/db/data.sqlite
Windows%APPDATA%\9router\db\data.sqlite
Docker/data/db/data.sqlite inside the container

Stop 9Router, start 9router-go, and log in with your existing password. Your provider connections, proxy pools, combos, API keys, model aliases, and usage history are all there — 9router-go's own dashboard renders them, because it *is* the same data.

You don't even have to stop 9Router if you want to keep the Node.js dashboard around. Run 9router-go on a different port against the same DATA_DIR:

# 9Router on :20128 (Next.js)  ·  9router-go on :20130 (Go, same DB)
PORT=20130 DATA_DIR=/home/you/.9router ./9router-go

Both read the same tables, so a connection you add in either dashboard shows up in the other. SQLite serialises the writes; the supported setup is one active writer, so avoid editing the same combo or settings entry in both at the same moment.

Running it the other way round (9router-go first, then pointing 9Router at the same directory) works the same way. 9router-go will have added two columns to providerConnections (lastUsedAt, consecutiveUseCount) and one extra table (upstream_leases). Upstream ignores both — its schema sync is additive and doesn't drop unknown columns — so nothing breaks.

What 9router-go will not do:

  • Import a legacy JSON export. If your 9Router data still lives in old JSON files, start upstream once to convert them, then switch.
  • Run destructive migrations or pre-migration backups. Its bootstrap only ever *adds* — create missing tables, add missing columns, seed missing rows. It never drops or retypes.
  • Interpret _meta.schemaVersion. It's upstream's migration bookkeeping. A database written by a much newer 9Router release should be checked before you rely on it.

Take a backup first if the database matters:

cp -r ~/.9router/db ~/9router-db-backup   # stop the daemon first — see DATABASE.md

Full schema, operator contract, and multi-process limits: DATABASE.md. Routing internals: ARCHITECTURE.md.


📸 Screenshots


⚙️ Setup Guide

Release binary

Download from GitHub Releases, verify against SHA256SUMS.txt.

OpenWrt

9router-go installs as an opkg package on OpenWrt 18.06 and later, with an optional LuCI page and a feed for upgrades:

echo "src/gz 9router-go https://luqman-v1.github.io/9router-go/openwrt/$(. /etc/openwrt_release && echo "$DISTRIB_ARCH")" \
	>> /etc/opkg/customfeeds.conf
opkg update && opkg install 9router-go luci-app-9router-go

Built for x86_64, i386, arm64 and armv7 targets. 32-bit MIPS routers are not covered: the pure-Go SQLite driver has no mips port.

Full details, including self-update vs opkg upgrade, the database backup helper and tunnels, in docs/OPENWRT.md.

🧪 Experimental builds

Unreleased work also ships as experimental builds. They are published separately and are never offered to a normal install:

  • GitHub Releases marks them Pre-release, so releases/latest — the URL 9router-go update falls back to — keeps pointing at the stable version.
  • Docker Hub tags them exp (luqmenul/9router-go:exp), never latest.

One-line install of the newest experimental build (no Docker, no build):

curl -fsSL https://raw.githubusercontent.com/luqman-v1/9router-go/main/install.sh \
  | VERSION=exp bash
# CPU without AVX? add VARIANT=noavx, or use install-noavx.sh with VERSION=exp.

VERSION=exp resolves the newest pre-release tag via the GitHub API, so the command keeps working as new experimental builds are published. Pin an exact tag (VERSION=v1.9.17-exp.10) if you need reproducibility.

Opt in only if you want to help shake out bugs. 9router-go update will not install one over a stable release.

Build from source

Prerequisites: Go 1.27 and Bun 1.x (dashboard is embedded into the binary, so build web first):

git clone https://github.com/luqman-v1/9router-go.git
cd 9router-go
make web-build   # bun install --frozen-lockfile && bun run build
make build       # embeds VERSION into the Go binary

Run

Defaults are enough for most people — plain 9router-go listens on port 20130 with data in ~/.9router:

9router-go
curl http://localhost:20130/health
./9router-go version

Only override when you need something different (PORT, DATA_DIR/DB_PATH — there are no --port flags):

PORT=20129 ./9router-go                        # different port
DATA_DIR=/srv/9router ./9router-go              # different data dir
DB_PATH=/srv/9router/data.sqlite ./9router-go   # explicit SQLite file
HOST=127.0.0.1 ./9router-go                     # localhost only, behind a reverse proxy

🔑 Dashboard Login & Fresh Install

  • Localhost (localhost / 127.0.0.1): First login uses the default compatibility password 123456. Once logged in, change your password in Settings → Profile.
  • Remote / VPS / Docker / LAN: For security (preventing public takeover of fresh installs with known defaults, CVE-2026-56679), remote access blocks the default 123456 password. You must either:
  1. Set INITIAL_PASSWORD on launch (Recommended): ``bash INITIAL_PASSWORD="your-secure-password" ./9router-go # Or in your .env file: # INITIAL_PASSWORD=your-secure-password ``
  2. Or access via SSH port-forwarding first: ``bash ssh -L 20130:127.0.0.1:20130 user@remote-host # Open http://localhost:20130, login with 123456, then change password in Settings ``

Client example

curl http://localhost:20130/v1/chat/completions \
  -H 'Content-Type: application/json' \
  -H 'Authorization: Bearer sk-your-api-key' \
  -d '{"model":"ag/gemini-3.8-flash-high","messages":[{"role":"user","content":"Hello"}],"stream":true}'

For Claude Messages clients: ANTHROPIC_BASE_URL=http://localhost:20130/v1.

Advanced: environment variables, API surface, auth, database

<
Visits:4 Updated:2026-12-03 AI tools

Related