Go HTTP Integration
Go projects can directly call CoreRouter using the standard library without depending on specific SDKs. This is suitable for server-side, command-line tools, and scenarios requiring full control over retries, timeouts, and logging.
Basic Request
go
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
)
func main() {
apiKey := os.Getenv("COREROUTER_API_KEY")
if apiKey == "" {
panic("missing COREROUTER_API_KEY")
}
baseURL := os.Getenv("COREROUTER_BASE_URL")
if baseURL == "" {
baseURL = "https://api.corerouter.cloud/v1"
}
modelID := os.Getenv("COREROUTER_MODEL")
if modelID == "" {
modelID = "claude-sonnet-4-5"
}
body, err := json.Marshal(map[string]interface{}{
"model": modelID,
"messages": []map[string]string{
{"role": "user", "content": "Hello, please introduce yourself."},
},
})
if err != nil {
panic(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(
ctx,
http.MethodPost,
strings.TrimRight(baseURL, "/")+"/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))
}Save the code as main.go, set the environment variables below in the same terminal, then run go run main.go. COREROUTER_BASE_URL should include /v1, not the full /chat/completions path; a trailing / is accepted. Copy the Model ID from the console into COREROUTER_MODEL; the example default is used only when that variable is unset.
Production Environment Recommendations
- Must set timeout; don't directly use requests without timeout control.
- Log
status_codeand error summary; don't log complete API Key. - Implement limited retries with exponential backoff for
429,502,503,504. - Make
model,base_url, and API Key configurable for easy model and environment switching. - Streaming output requires reading Server-Sent Events line by line; don't wait for entire response to finish.
Environment Variables
bash
export COREROUTER_API_KEY="sk-xxxxxxxxxxxxxxxx"
export COREROUTER_BASE_URL="https://api.corerouter.cloud/v1"
export COREROUTER_MODEL="claude-sonnet-4-5"When deploying to servers, containers, or CI, use the platform's Secret management feature to save API Keys.
