Go
使用 Go 标准库调用网关——无需第三方客户端。
两个端点都通过 HTTP 传输标准的 JSON,因此 net/http 就足够了。
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"os"
"time"
)
type msg struct {
Role string `json:"role"`
Content string `json:"content"`
}
type req struct {
Model string `json:"model"`
MaxTokens int `json:"max_tokens"`
Messages []msg `json:"messages"`
}
type resp struct {
Content []struct {
Text string `json:"text"`
} `json:"content"`
Usage struct {
InputTokens int `json:"input_tokens"`
OutputTokens int `json:"output_tokens"`
} `json:"usage"`
}
func main() {
body, _ := json.Marshal(req{
Model: "claude-sonnet-4-6",
MaxTokens: 1024,
Messages: []msg{{Role: "user", Content: "Hello"}},
})
r, _ := http.NewRequest("POST", "https:">//aiprimetech.io/v1/messages", bytes.NewReader(body))
r.Header.Set("x-api-key", os.Getenv("CLAUDEAPIKEY"))
r.Header.Set("anthropic-version", "2023-06-01")
r.Header.Set("content-type", "application/json")
client := &http.Client{Timeout: 120 * time.Second}
res, err := client.Do(r)
if err != nil {
panic(err)
}
defer res.Body.Close()
var out resp
json.NewDecoder(res.Body).Decode(&out)
fmt.Println(out.Content[0].Text)
fmt.Println(out.Usage.InputTokens, out.Usage.OutputTokens)
}
务必显式设置
Timeout 作为客户端的配置。Go 默认的 http.Client 没有此设置,因此连接停滞会无限期阻塞 goroutine。