Go
Preview
soxom.yaml
Terminal window
Guide to using Soxom-generated Go SDKs. The Go target aims to deliver
idiomatic Go (functional options, context.Context on every call, iterator
pagination, typed errors). The sections below describe the target surface;
not every feature is fully delivered yet, and parity with the TypeScript,
Python, and Java generators will arrive incrementally.
Configuration
Section titled “Configuration”targets: go: module: github.com/acme/sdk-go| Option | Default | Description |
|---|---|---|
module | - | Go module path (required) |
Installation
Section titled “Installation”go get github.com/acme/sdk-goClient Initialization
Section titled “Client Initialization”package main
import ( "context" "os"
acme "github.com/acme/sdk-go")
func main() { // With token client := acme.NewClient( acme.WithToken(os.Getenv("ACME_API_TOKEN")), )
// With options client := acme.NewClient( acme.WithToken(os.Getenv("ACME_API_TOKEN")), acme.WithBaseURL("https://api.acme.com/v2"), acme.WithTimeout(30 * time.Second), )
// From environment (if configured) client := acme.NewClient() // Reads from ACME_API_TOKEN}Context Usage
Section titled “Context Usage”All SDK methods require a context as the first argument:
ctx := context.Background()
// Simple requestuser, err := client.Users.Get(ctx, "user-123")
// With timeoutctx, cancel := context.WithTimeout(ctx, 5*time.Second)defer cancel()user, err := client.Users.Get(ctx, "user-123")
// With cancellationctx, cancel := context.WithCancel(ctx)go func() { // Cancel after some condition cancel()}()user, err := client.Users.Get(ctx, "user-123")Basic Operations
Section titled “Basic Operations”ctx := context.Background()
// Getuser, err := client.Users.Get(ctx, "user-123")if err != nil { log.Fatal(err)}fmt.Println(user.Name)
// CreatenewUser, err := client.Users.Create(ctx, acme.UserCreate{ Email: "john@example.com", Name: "John Doe",})
// Updateupdated, err := client.Users.Update(ctx, "user-123", acme.UserUpdate{ Name: acme.String("Jane Doe"), // Optional field helper})
// Deleteerr = client.Users.Delete(ctx, "user-123")Type Safety
Section titled “Type Safety”Go SDK uses strongly typed structs:
// Request typesreq := acme.UserCreate{ Email: "john@example.com", // Required field Name: "John Doe", // Required field}
// Optional fields use pointers or helper functionsreq := acme.UserUpdate{ Name: acme.String("New Name"), // *string Status: acme.UserStatus("active"), // Optional enum}
// Response typesuser, _ := client.Users.Get(ctx, "user-123")fmt.Println(user.ID) // stringfmt.Println(user.Email) // stringfmt.Println(user.Status) // acme.UserStatusfmt.Println(user.CreatedAt) // time.TimeUnion Types
Section titled “Union Types”// Union types use interfacestype PaymentMethod interface { isPaymentMethod()}
// Type switch for handlingfunc processPayment(method acme.PaymentMethod) { switch m := method.(type) { case acme.CreditCard: fmt.Printf("Card: %s\n", m.CardNumber) case acme.BankAccount: fmt.Printf("Account: %s\n", m.AccountNumber) }}Pagination
Section titled “Pagination”Iterator Pattern
Section titled “Iterator Pattern”// Iterate through all pagesiter := client.Users.List(ctx)for iter.Next() { user := iter.Current() fmt.Println(user.Name)}if err := iter.Err(); err != nil { log.Fatal(err)}
// With optionsiter := client.Users.List(ctx, acme.ListUsersParams{ Status: acme.String("active"), Limit: acme.Int(50),})Manual Pagination
Section titled “Manual Pagination”// Get first pagepage, err := client.Users.ListPage(ctx, acme.ListUsersParams{ Limit: acme.Int(10),})if err != nil { log.Fatal(err)}
for _, user := range page.Data { fmt.Println(user.Name)}
// Get next pageif page.HasMore { nextPage, err := client.Users.ListPage(ctx, acme.ListUsersParams{ After: page.NextCursor, Limit: acme.Int(10), })}Streaming
Section titled “Streaming”// SSE streamingstream, err := client.Chat.Completions.Create(ctx, acme.ChatCompletionRequest{ Model: "gpt-4", Messages: []acme.ChatMessage{ {Role: "user", Content: "Hello"}, }, Stream: true,})if err != nil { log.Fatal(err)}defer stream.Close()
for stream.Next() { chunk := stream.Current() if content := chunk.Choices[0].Delta.Content; content != "" { fmt.Print(content) }}if err := stream.Err(); err != nil { log.Fatal(err)}Error Handling
Section titled “Error Handling”import "errors"
user, err := client.Users.Get(ctx, "user-123")if err != nil { var apiErr *acme.APIError if errors.As(err, &apiErr) { switch apiErr.StatusCode { case 401: fmt.Println("Authentication failed") case 404: fmt.Println("User not found") case 429: fmt.Printf("Rate limited. Retry after %d seconds\n", apiErr.RetryAfter) default: fmt.Printf("API error: %d - %s\n", apiErr.StatusCode, apiErr.Message) } return }
// Network or other errors log.Fatal(err)}Error Types
Section titled “Error Types”// Check specific error typesvar notFoundErr *acme.NotFoundErrorif errors.As(err, ¬FoundErr) { fmt.Println("Resource not found:", notFoundErr.Resource)}
var rateLimitErr *acme.RateLimitErrorif errors.As(err, &rateLimitErr) { time.Sleep(time.Duration(rateLimitErr.RetryAfter) * time.Second) // Retry...}
var validationErr *acme.ValidationErrorif errors.As(err, &validationErr) { for _, e := range validationErr.Errors { fmt.Printf("Field %s: %s\n", e.Field, e.Message) }}Request Options
Section titled “Request Options”Override settings per-request using functional options:
// Custom timeoutreport, err := client.Reports.Generate(ctx, params, acme.WithRequestTimeout(2 * time.Minute),)
// Disable retriespayment, err := client.Payments.Create(ctx, data, acme.WithRetries(acme.RetryConfig{Enabled: false}),)
// Custom headersresult, err := client.Users.List(ctx, acme.WithHeader("X-Custom-Header", "value"),)
// Idempotency keyorder, err := client.Orders.Create(ctx, data, acme.WithIdempotencyKey("unique-request-123"),)Naming Conventions
Section titled “Naming Conventions”Go SDK follows Go naming conventions:
| OpenAPI | Go |
|---|---|
user_name | UserName |
created_at | CreatedAt |
api_key | APIKey |
list method | List |
get method | Get |
Generated Package Structure
Section titled “Generated Package Structure”github.com/acme/sdk-go/├── client.go # Client type├── options.go # Client options├── users.go # Users resource├── orders.go # Orders resource├── types.go # Shared types├── errors.go # Error types├── go.mod├── go.sum└── README.md