SDK Documentation

Go SDK

High-performance SDK with goroutine support and minimal overhead

Go 1.19+
Version Support
Zero
Dependencies
< 1ms
Overhead

Installation

Install with go get

go get github.com/the-autonoma/go-sdk

Add to go.mod

require github.com/the-autonoma/go-sdk v2.0.0

Import in Your Code

import "github.com/the-autonoma/go-sdk/autonoma"

Quick Start

Basic Usage

package main

import (
    "context"
    "fmt"
    "log"
    "os"
    
    "github.com/the-autonoma/go-sdk/autonoma"
)

func main() {
    // Initialize client
    client, err := autonoma.New(
        autonoma.WithAPIKey(os.Getenv("AUTONOMA_API_KEY")),
        autonoma.WithEnvironment("production"),
    )
    if err != nil {
        log.Fatal(err)
    }
    defer client.Close()
    
    // Start monitoring
    client.Start()
    
    // Analyze code
    content, _ := os.ReadFile("main.go")
    analysis, err := client.Analyze(context.Background(), &autonoma.AnalyzeOptions{
        File:    "main.go",
        Content: string(content),
    })
    if err != nil {
        log.Fatal(err)
    }
    
    // Get predictions
    predictions, err := client.GetPredictions(context.Background(), nil)
    if err != nil {
        log.Fatal(err)
    }
    
    // Apply auto-fix
    for _, pred := range predictions {
        if pred.AutoFixAvailable {
            result, err := client.ApplyFix(context.Background(), pred.ID, nil)
            if err != nil {
                log.Printf("Fix failed: %v", err)
                continue
            }
            fmt.Printf("Fix applied: %v\n", result.Success)
        }
    }
}

Concurrent Analysis

package main

import (
    "context"
    "path/filepath"
    "sync"
    
    "github.com/the-autonoma/go-sdk/autonoma"
)

func analyzeProject(client *autonoma.Client) error {
    files, err := filepath.Glob("**/*.go")
    if err != nil {
        return err
    }
    
    ctx := context.Background()
    var wg sync.WaitGroup
    results := make(chan *autonoma.AnalysisResult, len(files))
    errors := make(chan error, len(files))
    
    // Analyze files concurrently
    for _, file := range files {
        wg.Add(1)
        go func(f string) {
            defer wg.Done()
            
            content, err := os.ReadFile(f)
            if err != nil {
                errors <- err
                return
            }
            
            result, err := client.Analyze(ctx, &autonoma.AnalyzeOptions{
                File:    f,
                Content: string(content),
            })
            if err != nil {
                errors <- err
                return
            }
            
            results <- result
        }(file)
    }
    
    // Wait for all goroutines
    go func() {
        wg.Wait()
        close(results)
        close(errors)
    }()
    
    // Process results
    var totalIssues int
    for result := range results {
        totalIssues += len(result.Predictions)
        fmt.Printf("%s: %d issues found\n", result.File, len(result.Predictions))
    }
    
    // Check for errors
    select {
    case err := <-errors:
        return err
    default:
        fmt.Printf("Total issues found: %d\n", totalIssues)
        return nil
    }
}

HTTP Middleware

package main

import (
    "net/http"
    
    "github.com/the-autonoma/go-sdk/autonoma"
    "github.com/the-autonoma/go-sdk/middleware"
)

func main() {
    // Initialize client
    client, _ := autonoma.New(
        autonoma.WithAPIKey("your-api-key"),
    )
    
    // Create middleware
    autonomaMiddleware := middleware.New(client, &middleware.Config{
        CaptureErrors:      true,
        CapturePerformance: true,
        CaptureHeaders:     true,
        SampleRate:         1.0,
    })
    
    // Standard net/http
    mux := http.NewServeMux()
    mux.HandleFunc("/api/users", handleUsers)
    
    // Wrap with middleware
    handler := autonomaMiddleware.Handler(mux)
    http.ListenAndServe(":8080", handler)
}

// With popular frameworks

// Gin
import "github.com/gin-gonic/gin"

router := gin.New()
router.Use(middleware.Gin(client))

// Echo
import "github.com/labstack/echo/v4"

e := echo.New()
e.Use(middleware.Echo(client))

// Chi
import "github.com/go-chi/chi/v5"

r := chi.NewRouter()
r.Use(middleware.Chi(client))

gRPC Integration

package main

import (
    "google.golang.org/grpc"
    
    "github.com/the-autonoma/go-sdk/autonoma"
    "github.com/the-autonoma/go-sdk/interceptors"
)

func main() {
    // Initialize client
    client, _ := autonoma.New(
        autonoma.WithAPIKey("your-api-key"),
    )
    
    // Create gRPC interceptors
    unaryInterceptor := interceptors.UnaryServerInterceptor(client)
    streamInterceptor := interceptors.StreamServerInterceptor(client)
    
    // Create gRPC server with interceptors
    server := grpc.NewServer(
        grpc.UnaryInterceptor(unaryInterceptor),
        grpc.StreamInterceptor(streamInterceptor),
    )
    
    // Register your services
    pb.RegisterUserServiceServer(server, &userService{})
    
    // Start server
    lis, _ := net.Listen("tcp", ":50051")
    server.Serve(lis)
}

// Client-side interceptors
func createGRPCClient() pb.UserServiceClient {
    unaryInterceptor := interceptors.UnaryClientInterceptor(client)
    streamInterceptor := interceptors.StreamClientInterceptor(client)
    
    conn, _ := grpc.Dial("localhost:50051",
        grpc.WithUnaryInterceptor(unaryInterceptor),
        grpc.WithStreamInterceptor(streamInterceptor),
    )
    
    return pb.NewUserServiceClient(conn)
}

Configuration Options

package main

import (
    "time"
    
    "github.com/the-autonoma/go-sdk/autonoma"
)

func main() {
    // Full configuration
    client, err := autonoma.New(
        // Required
        autonoma.WithAPIKey("your-api-key"),
        
        // Environment
        autonoma.WithEnvironment("production"),
        
        // API Configuration
        autonoma.WithBaseURL("https://api.autonoma.dev"),
        autonoma.WithTimeout(30 * time.Second),
        autonoma.WithRetries(3),
        autonoma.WithRetryDelay(time.Second),
        
        // Features
        autonoma.WithAutoFix(&autonoma.AutoFixConfig{
            Enabled:          true,
            Confidence:       0.95,
            RequireApproval:  false,
            ExcludePatterns:  []string{"*_test.go", "vendor/*"},
            MaxFixesPerRun:   10,
        }),
        
        // Monitoring
        autonoma.WithMonitoring(&autonoma.MonitoringConfig{
            Errors:          true,
            Performance:     true,
            CustomMetrics:   true,
            SamplingRate:    1.0,
            CaptureGoroutines: true,
        }),
        
        // Security
        autonoma.WithEncryption(true),
        autonoma.WithAnonymization(&autonoma.AnonymizeConfig{
            Enabled: true,
            Fields:  []string{"password", "apiKey", "email"},
        }),
        
        // Performance
        autonoma.WithBatchSize(100),
        autonoma.WithFlushInterval(5 * time.Second),
        autonoma.WithWorkerCount(4),
        
        // Logging
        autonoma.WithLogger(customLogger),
        autonoma.WithDebug(true),
        
        // Callbacks
        autonoma.WithOnPrediction(func(p *autonoma.Prediction) {
            log.Printf("New prediction: %s", p.Message)
        }),
        autonoma.WithOnFix(func(f *autonoma.Fix) {
            log.Printf("Fix applied: %s", f.ID)
        }),
        autonoma.WithOnError(func(err error) {
            log.Printf("Autonoma error: %v", err)
        }),
    )
    
    if err != nil {
        log.Fatal(err)
    }
    defer client.Close()
}

// Configuration from file
func loadFromConfig() (*autonoma.Client, error) {
    config, err := autonoma.LoadConfig("autonoma.yaml")
    if err != nil {
        return nil, err
    }
    
    return autonoma.NewWithConfig(config)
}

// Environment variables
// AUTONOMA_API_KEY
// AUTONOMA_ENVIRONMENT
// AUTONOMA_BASE_URL
// AUTONOMA_DEBUG
client, err := autonoma.NewFromEnv()

Configuration File

YAML configuration example:

# autonoma.yaml
apiKey: ${AUTONOMA_API_KEY}
environment: production
autoFix:
  enabled: true
  confidence: 0.95
monitoring:
  errors: true
  performance: true

Context Support

All methods support context for cancellation:

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

result, err := client.Analyze(ctx, options)

Core Methods

Analyze(ctx, options)

Analyze code for potential issues, performance problems, and security vulnerabilities.

// Single file analysis
result, err := client.Analyze(ctx, &autonoma.AnalyzeOptions{
    File:    "main.go",
    Content: string(content),
    Context: map[string]interface{}{
        "goVersion": "1.21",
        "module":    "github.com/example/app",
    },
})

// Batch analysis
results, err := client.AnalyzeBatch(ctx, []*autonoma.AnalyzeOptions{
    {File: "main.go", Content: mainContent},
    {File: "handler.go", Content: handlerContent},
})

// With specific rules
result, err := client.Analyze(ctx, &autonoma.AnalyzeOptions{
    File:    "api.go",
    Content: content,
    Rules:   []string{"security", "performance"},
    Severity: autonoma.SeverityMedium,
})

// Process results
if result != nil {
    fmt.Printf("Found %d issues in %s:\n", len(result.Predictions), result.File)
    for _, pred := range result.Predictions {
        fmt.Printf("  [%s] Line %d: %s\n", pred.Severity, pred.Line, pred.Message)
    }
}

GetPredictions(ctx, filters)

Retrieve predictions for your codebase with optional filtering.

// Get all predictions
predictions, err := client.GetPredictions(ctx, nil)

// Filter by severity and type
filters := &autonoma.PredictionFilters{
    Severity: []autonoma.Severity{
        autonoma.SeverityCritical,
        autonoma.SeverityHigh,
    },
    Type:   "security",
    Status: autonoma.StatusOpen,
}
predictions, err := client.GetPredictions(ctx, filters)

// With pagination
page := &autonoma.PaginationOptions{
    Page:    1,
    PerPage: 50,
    OrderBy: "severity",
    Order:   autonoma.OrderDesc,
}
predictions, err := client.GetPredictionsWithPagination(ctx, filters, page)

// Iterate through predictions
for _, pred := range predictions {
    fmt.Printf("%s:%d - %s (Confidence: %.2f)\n",
        pred.File, pred.Line, pred.Message, pred.Confidence)
    
    if pred.AutoFixAvailable {
        fmt.Printf("  Auto-fix available: %s\n", pred.FixDescription)
    }
}

ApplyFix(ctx, predictionID, options)

Apply an auto-fix for a specific prediction with validation and rollback support.

// Apply fix with default settings
result, err := client.ApplyFix(ctx, "pred_123abc", nil)

// Apply with options
options := &autonoma.FixOptions{
    DryRun:        true,  // Preview changes
    CreateBackup:  true,  // Backup before applying
    RunTests:      true,  // Run tests after fix
    TestCommand:   "go test ./...",
    AutoCommit:    false,
    CommitMessage: "fix: resolve race condition in handler",
}
result, err := client.ApplyFix(ctx, "pred_123abc", options)

// Handle result
if err != nil {
    log.Printf("Fix failed: %v", err)
    return
}

if result.Success {
    fmt.Printf("Fix applied successfully!\n")
    fmt.Printf("Files changed: %d\n", len(result.FilesChanged))
    fmt.Printf("Lines modified: %d\n", result.LinesModified)
    
    // Review changes
    for _, change := range result.Changes {
        fmt.Printf("  %s: %s\n", change.File, change.Description)
    }
} else {
    fmt.Printf("Fix failed: %s\n", result.Error)
    
    // Rollback if available
    if result.RollbackID != "" {
        err := client.Rollback(ctx, result.RollbackID)
        if err != nil {
            log.Printf("Rollback failed: %v", err)
        }
    }
}

// Batch fixes
var predictionIDs []string
for _, pred := range predictions {
    if pred.AutoFixAvailable && pred.Confidence > 0.95 {
        predictionIDs = append(predictionIDs, pred.ID)
    }
}

results, err := client.ApplyFixes(ctx, predictionIDs, &autonoma.BatchFixOptions{
    StopOnError: true,
    Parallel:    false,
})

Monitoring Methods

Monitor application performance and errors in real-time.

// Start monitoring
client.Start()
defer client.Stop()

// Capture errors
defer func() {
    if r := recover(); r != nil {
        client.CaptureError(fmt.Errorf("panic: %v", r))
    }
}()

// Custom error handling
if err != nil {
    client.CaptureError(err, &autonoma.ErrorOptions{
        User: userID,
        Tags: map[string]string{
            "component": "payment",
            "version":   "2.1.0",
        },
        Extra: map[string]interface{}{
            "orderID": orderID,
            "amount":  amount,
        },
    })
}

// Performance monitoring
timer := client.StartTimer("database.query")
result := db.Query(sql)
timer.End()

// Custom metrics
client.Metric("api.requests", 1, &autonoma.MetricOptions{
    Tags: map[string]string{
        "endpoint": "/api/users",
        "method":   "GET",
    },
})

client.Gauge("queue.size", queue.Size())
client.Histogram("response.size", len(response))

// Distributed tracing
span := client.StartSpan("process_order")
defer span.Finish()

span.SetTag("order.id", orderID)
span.SetTag("user.id", userID)

// Child spans
childSpan := span.StartChild("validate_payment")
// ... do work
childSpan.Finish()

Advanced Features

Custom Rules

// Define custom rule
rule := &autonoma.Rule{
    ID:       "no-fmt-print",
    Name:     "No fmt.Print in production",
    Severity: autonoma.SeverityWarning,
    Pattern:  "fmt\.Print(ln)?\\(",
    Message:  "Use structured logging instead",
    Fix: func(match string) string {
        return "log.Printf("
    },
}

client.AddRule(rule)

// Rule set
ruleSet := &autonoma.RuleSet{
    Name: "company-standards",
    Rules: []*autonoma.Rule{
        {
            ID:      "error-handling",
            Pattern: "if err != nil \\{\\s*\\}",
            Message: "Empty error handling",
        },
        {
            ID:      "context-timeout",
            Pattern: "context\.Background\\(\\)",
            Message: "Use context with timeout",
        },
    },
}

client.AddRuleSet(ruleSet)

Hooks and Plugins

// Pre-analysis hook
client.AddHook(autonoma.HookPreAnalyze, func(ctx context.Context, opts *autonoma.AnalyzeOptions) error {
    // Validate or modify options
    if strings.HasSuffix(opts.File, "_gen.go") {
        return autonoma.ErrSkipFile
    }
    return nil
})

// Post-fix hook
client.AddHook(autonoma.HookPostFix, func(ctx context.Context, result *autonoma.FixResult) error {
    // Run additional validation
    cmd := exec.Command("go", "test", "./...")
    if err := cmd.Run(); err != nil {
        return fmt.Errorf("tests failed after fix: %w", err)
    }
    return nil
})

// Custom plugin
type SlackPlugin struct {
    webhook string
}

func (p *SlackPlugin) OnPrediction(pred *autonoma.Prediction) {
    if pred.Severity == autonoma.SeverityCritical {
        // Send Slack notification
    }
}

client.RegisterPlugin(&SlackPlugin{
    webhook: "https://hooks.slack.com/...",
})

Testing Support

import (
    "testing"
    "github.com/the-autonoma/go-sdk/autonoma/mock"
)

func TestUserHandler(t *testing.T) {
    // Create mock client
    mockClient := mock.NewClient()
    
    // Set expectations
    mockClient.ExpectAnalyze(&autonoma.AnalyzeOptions{
        File: "handler.go",
    }).Return(&autonoma.AnalysisResult{
        Predictions: []*autonoma.Prediction{
            {
                ID:       "pred_123",
                Message:  "Potential nil pointer",
                Severity: autonoma.SeverityMedium,
            },
        },
    }, nil)
    
    // Test your code
    handler := NewHandler(mockClient)
    err := handler.Process()
    
    // Verify expectations
    mockClient.AssertExpectations(t)
}

// Test helpers
func TestWithAutonoma(t *testing.T) {
    client := autonoma.NewTestClient(t)
    defer client.Close()
    
    // Automatically analyze test code
    client.AnalyzeTest(t)
    
    // Your test code
    result := MyFunction()
    assert.Equal(t, expected, result)
    
    // Check for issues
    client.AssertNoIssues(t)
}

CLI Integration

# Install CLI
$ go install github.com/the-autonoma/go-sdk/cmd/autonoma@latest

# Initialize project
$ autonoma init
✓ Created autonoma.yaml

# Analyze project
$ autonoma analyze ./...
Analyzing 45 Go files...
Found 12 issues (2 critical, 5 high, 5 medium)

# View predictions
$ autonoma predictions --format=table
┌─────────────┬──────────┬────────────────┐
│ ID          │ Severity │ Message        │
├─────────────┼──────────┼────────────────┤
│ pred_abc123 │ Critical │ Race condition │
└─────────────┴──────────┴────────────────┘

# Apply fixes
$ autonoma fix --auto --confidence=0.95
✓ Applied 8 fixes

# Generate report
$ autonoma report --format=html > report.html

# CI mode
$ autonoma ci --fail-on=high
✓ No high severity issues found

Performance Optimization

Zero Allocation Monitoring

// Use sync.Pool for zero allocations
client, _ := autonoma.New(
    autonoma.WithAPIKey("key"),
    autonoma.WithZeroAllocation(true),
)

// Pre-allocate buffers
buffer := make([]byte, 4096)
client.SetBuffer(buffer)

// Benchmark results
// BenchmarkAnalyze-8      1000000      1053 ns/op       0 B/op       0 allocs/op
// BenchmarkMetric-8      10000000       152 ns/op       0 B/op       0 allocs/op

Batch Processing

// Configure batching
client, _ := autonoma.New(
    autonoma.WithBatchSize(1000),
    autonoma.WithFlushInterval(100 * time.Millisecond),
)

// Batch operations are automatic
for i := 0; i < 10000; i++ {
    client.Metric("processed", 1) // Batched automatically
}

// Force flush
client.Flush()

// Custom batch processor
processor := autonoma.NewBatchProcessor(client, &autonoma.BatchConfig{
    MaxSize:     5000,
    MaxWait:     time.Second,
    Concurrency: 4,
})

// Add items to batch
for _, file := range files {
    processor.Add(&autonoma.AnalyzeOptions{
        File:    file,
        Content: readFile(file),
    })
}

// Process batch
results, err := processor.Process(ctx)

Error Handling

package main

import (
    "errors"
    "log"
    
    "github.com/the-autonoma/go-sdk/autonoma"
)

func handleAutonomaErrors() {
    result, err := client.Analyze(ctx, options)
    if err != nil {
        var apiErr *autonoma.APIError
        var validationErr *autonoma.ValidationError
        var rateLimitErr *autonoma.RateLimitError
        
        switch {
        case errors.As(err, &apiErr):
            log.Printf("API error: %d - %s", apiErr.StatusCode, apiErr.Message)
            
        case errors.As(err, &validationErr):
            log.Printf("Validation error: %s", validationErr.Field)
            for _, e := range validationErr.Errors {
                log.Printf("  - %s: %s", e.Field, e.Message)
            }
            
        case errors.As(err, &rateLimitErr):
            log.Printf("Rate limit exceeded, retry after: %v", rateLimitErr.RetryAfter)
            time.Sleep(rateLimitErr.RetryAfter)
            // Retry operation
            
        case errors.Is(err, autonoma.ErrUnauthorized):
            log.Fatal("Invalid API key")
            
        case errors.Is(err, autonoma.ErrNetworkError):
            log.Printf("Network error: %v", err)
            // Implement retry logic
            
        default:
            log.Printf("Unknown error: %v", err)
        }
    }
}

// Retry with exponential backoff
func retryWithBackoff(fn func() error) error {
    backoff := time.Second
    maxRetries := 5
    
    for i := 0; i < maxRetries; i++ {
        err := fn()
        if err == nil {
            return nil
        }
        
        var rateLimitErr *autonoma.RateLimitError
        if errors.As(err, &rateLimitErr) {
            time.Sleep(rateLimitErr.RetryAfter)
            continue
        }
        
        if i < maxRetries-1 {
            time.Sleep(backoff)
            backoff *= 2
        }
    }
    
    return fmt.Errorf("max retries exceeded")
}

Best Practices

Resource Management

  • • Always defer client.Close()
  • • Use context for cancellation
  • • Handle goroutine leaks properly
  • • Set appropriate timeouts

Performance

  • • Enable batching for high throughput
  • • Use zero allocation mode when possible
  • • Implement proper connection pooling
  • • Cache analysis results appropriately

Security

  • • Store API keys securely
  • • Enable encryption for sensitive code
  • • Use environment variables
  • • Implement proper error handling

Integration

  • • Add to CI/CD pipelines
  • • Use git hooks for pre-commit checks
  • • Enable monitoring in production
  • • Implement gradual rollout

Ready to Get Started?

Install the Go SDK and start improving your code quality