Skip to content
On this page

Go HTTP 接入

Go 项目可以直接使用标准库调用 CoreRouter,不依赖特定 SDK。这样适合服务端、命令行工具和需要完全控制重试、超时、日志的场景。

基础请求

go
package main

import (
	"bytes"
	"context"
	"fmt"
	"io"
	"net/http"
	"os"
	"time"
)

func main() {
	apiKey := os.Getenv("COREROUTER_API_KEY")
	if apiKey == "" {
		panic("missing COREROUTER_API_KEY")
	}

	body := []byte(`{
		"model": "claude-sonnet-4-5",
		"messages": [
			{"role": "user", "content": "你好,请介绍一下你自己。"}
		]
	}`)

	ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
	defer cancel()

	req, err := http.NewRequestWithContext(
		ctx,
		http.MethodPost,
		"https://api.corerouter.tech/v1/chat/completions",
		bytes.NewReader(body),
	)
	if err != nil {
		panic(err)
	}

	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer "+apiKey)

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	data, err := io.ReadAll(resp.Body)
	if err != nil {
		panic(err)
	}

	if resp.StatusCode < 200 || resp.StatusCode >= 300 {
		panic(fmt.Sprintf("request failed: %s\n%s", resp.Status, data))
	}

	fmt.Println(string(data))
}

生产环境建议

  • 必须设置超时,不要直接使用没有超时控制的请求。
  • 记录 status_code 和错误摘要,不要记录完整 API Key。
  • 对 429、502、503、504 做有限次数重试,并使用指数退避。
  • 把 model、base_url 和 API Key 做成配置项,便于切换模型和环境。
  • 流式输出需要按行读取 Server-Sent Events,不要等待整个响应结束。

环境变量

bash
export COREROUTER_API_KEY="sk-xxxxxxxxxxxxxxxx"
export COREROUTER_BASE_URL="https://api.corerouter.tech/v1"
export COREROUTER_MODEL="claude-sonnet-4-5"

部署到服务器、容器或 CI 时,使用平台的 Secret 管理功能保存 API Key。

Released under the MIT License.