Comprehensive examples demonstrating various patterns for building applications with the Claude SDK Go streaming interface.
This example collection showcases 8 different patterns for interactive client usage:
- basic - Basic streaming with context manager
- multi_turn - Multi-turn conversations
- concurrent - Concurrent send/receive using goroutines
- interrupt - Interrupt capability demonstration
- manual - Manual message stream handling with custom logic
- options - Using ClaudeAgentOptions for configuration
- bash - Tool use blocks when running bash commands
- control - Control protocol capabilities (SetPermissionMode, SetModel)
Run a specific example:
go run main.go <example_name>Run all examples sequentially:
go run main.go allList available examples:
go run main.goSimple query and response pattern using the helper method ReceiveResponse().
go run main.go basicDemonstrates maintaining context across multiple conversation turns.
go run main.go multi_turnShows how to handle responses while sending new messages using goroutines and channels.
go run main.go concurrentDemonstrates how to interrupt a long-running task and send a new query.
go run main.go interruptProcess messages manually with custom logic - extracts programming language names from responses.
go run main.go manualConfigure the client with ClaudeAgentOptions including allowed tools, system prompts, and permission modes.
go run main.go optionsShows tool use blocks when Claude executes bash commands.
go run main.go bashDemonstrates runtime control capabilities like changing permission modes and models.
go run main.go controlAll examples use context.WithTimeout for proper lifecycle management:
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()client := claudesdk.NewClient(log)
defer client.Close()
if err := client.Connect(ctx, options); err != nil {
// handle error
}// Iterator-based response (stops at ResultMessage)
for msg, err := range client.ReceiveResponse(ctx) {
if err != nil {
// handle error
break
}
// process message
}
// Continuous message streaming (yields indefinitely)
for msg, err := range client.ReceiveMessages(ctx) {
if err != nil {
break
}
// process message
if _, ok := msg.(*claudesdk.ResultMessage); ok {
break // exit when done
}
}var wg sync.WaitGroup
done := make(chan struct{})
wg.Add(1)
go func() {
defer wg.Done()
// Use iter.Pull2 for pull-based iteration in goroutines with select
next, stop := iter.Pull2(client.ReceiveMessages(ctx))
defer stop()
for {
select {
case <-done:
return
default:
msg, err, ok := next()
if !ok || err != nil {
return
}
// process message
}
}
}()
// ... do work ...
close(done)
wg.Wait()The queries in these examples are intentionally simplistic. In real applications, queries can be complex tasks where Claude SDK uses its agentic capabilities and tools (bash commands, file operations, web search, etc.) to accomplish goals.