Options API Reference¶
The Options type allows you to configure the Socket.IO client behavior.
Table of Contents¶
Definition¶
type Options struct {
Auth map[string]interface{}
Headers map[string]string
ReconnectAttempts int
ReconnectDelay time.Duration
ReconnectDelayMax time.Duration
Timeout time.Duration
AckTimeout time.Duration
}
All options are optional. If not specified, reasonable defaults are used.
Authentication Options¶
Auth¶
Authentication data sent during the initial handshake. Useful for JWT tokens, credentials, etc.
Type: map[string]interface{} Default value: nil (no authentication)
Example:
client := socketio.New("ws://localhost:3000", socketio.Options{
Auth: map[string]interface{}{
"token": "eyJhbGciOiJIUzI1NiIs...",
},
})
Example with JWT:
client := socketio.New("ws://localhost:3000", socketio.Options{
Auth: map[string]interface{}{
"token": jwtToken,
"userId": "user-123",
},
})
Example with credentials:
client := socketio.New("ws://localhost:3000", socketio.Options{
Auth: map[string]interface{}{
"username": "juan",
"password": "secreto",
},
})
Headers¶
Custom HTTP headers sent during the initial connection.
Type: map[string]string Default value: nil (no custom headers)
Example:
client := socketio.New("ws://localhost:3000", socketio.Options{
Headers: map[string]string{
"Authorization": "Bearer token-123",
"X-API-Key": "api-key-456",
"User-Agent": "MiApp/1.0",
},
})
Reconnection Options¶
ReconnectAttempts¶
Maximum number of reconnection attempts before giving up.
Type: int Default value: 5 Special value: -1 = infinite attempts
Example:
// 10 reconnection attempts
client := socketio.New("ws://localhost:3000", socketio.Options{
ReconnectAttempts: 10,
})
// Infinite attempts (use with caution)
client := socketio.New("ws://localhost:3000", socketio.Options{
ReconnectAttempts: -1,
})
// No automatic reconnection
client := socketio.New("ws://localhost:3000", socketio.Options{
ReconnectAttempts: 0,
})
ReconnectDelay¶
Initial delay before the first reconnection attempt. This value increases exponentially on each attempt.
Type: time.Duration Default value: 1 * time.Second
Example:
// Wait 2 seconds before the first attempt
client := socketio.New("ws://localhost:3000", socketio.Options{
ReconnectDelay: 2 * time.Second,
})
// Fast reconnection (500ms)
client := socketio.New("ws://localhost:3000", socketio.Options{
ReconnectDelay: 500 * time.Millisecond,
})
ReconnectDelayMax¶
Maximum delay between reconnection attempts. Exponential backoff will not exceed this value.
Type: time.Duration Default value: 5 * time.Second
Example:
// Limit maximum delay to 10 seconds
client := socketio.New("ws://localhost:3000", socketio.Options{
ReconnectDelay: time.Second,
ReconnectDelayMax: 10 * time.Second,
})
Exponential backoff behavior:
// With ReconnectDelay = 1s and ReconnectDelayMax = 5s:
// Attempt 1: wait 1s
// Attempt 2: wait 2s
// Attempt 3: wait 4s
// Attempt 4: wait 5s (capped by ReconnectDelayMax)
// Attempt 5: wait 5s
Timeout Options¶
Timeout¶
Timeout for establishing the initial connection.
Type: time.Duration Default value: 20 * time.Second
Example:
// 30 second timeout for slow connection
client := socketio.New("ws://localhost:3000", socketio.Options{
Timeout: 30 * time.Second,
})
// Short timeout for fast failure (5 seconds)
client := socketio.New("ws://localhost:3000", socketio.Options{
Timeout: 5 * time.Second,
})
AckTimeout¶
Global timeout for waiting for acknowledgments. If the server does not respond within this time, the acknowledgment callback receives nil.
Type: time.Duration Default value: 5 * time.Second
Example:
// 10 second timeout for slow operations
client := socketio.New("ws://localhost:3000", socketio.Options{
AckTimeout: 10 * time.Second,
})
client.EmitWithAck("slow-operation", func(response ...interface{}) {
if response == nil {
fmt.Println("Timeout: operation took more than 10 seconds")
return
}
fmt.Println("Response:", response[0])
}, "datos")
Connection Options¶
Path¶
Note: This option is not implemented in the current struct, but may be added in the future.
The path of the Socket.IO endpoint on the server.
Default value: /socket.io/
Examples¶
Basic Configuration¶
client := socketio.New("ws://localhost:3000", socketio.Options{
ReconnectAttempts: 5,
Timeout: 30 * time.Second,
})
Configuration with Authentication¶
client := socketio.New("ws://api.example.com", socketio.Options{
Auth: map[string]interface{}{
"token": "eyJhbGciOiJIUzI1NiIs...",
"userId": "user-123",
},
Headers: map[string]string{
"Authorization": "Bearer token-456",
},
})
Configuration for Aggressive Reconnection¶
client := socketio.New("ws://localhost:3000", socketio.Options{
ReconnectAttempts: 10,
ReconnectDelay: 500 * time.Millisecond, // Try quickly
ReconnectDelayMax: 3 * time.Second, // But don't wait too long
})
Configuration for Slow Connections¶
client := socketio.New("ws://slow-server.example.com", socketio.Options{
Timeout: 60 * time.Second, // Long timeout for connection
AckTimeout: 30 * time.Second, // Long timeout for responses
})
Configuration Without Reconnection¶
// For cases where you don't want automatic reconnection
client := socketio.New("ws://localhost:3000", socketio.Options{
ReconnectAttempts: 0, // Disable reconnection
})
client.OnDisconnect(func(reason string) {
fmt.Println("Disconnected, no reconnection attempts")
// Implement custom logic here
})
Complete Configuration¶
client := socketio.New("wss://api.example.com", socketio.Options{
// Authentication
Auth: map[string]interface{}{
"token": getAuthToken(),
"userId": getCurrentUserId(),
"deviceId": getDeviceId(),
},
// Custom headers
Headers: map[string]string{
"Authorization": "Bearer " + getJWT(),
"X-API-Key": "api-key-123",
"X-Client-Version": "1.0.0",
},
// Configured reconnection
ReconnectAttempts: 10,
ReconnectDelay: time.Second,
ReconnectDelayMax: 5 * time.Second,
// Configured timeouts
Timeout: 30 * time.Second,
AckTimeout: 10 * time.Second,
})
Dynamic Configuration¶
func createClient(userType string) *socketio.Socket {
opts := socketio.Options{
ReconnectAttempts: 5,
Timeout: 20 * time.Second,
}
// User type-specific configuration
switch userType {
case "admin":
opts.Auth = map[string]interface{}{
"token": getAdminToken(),
"role": "admin",
}
opts.ReconnectAttempts = 10 // More attempts for admins
case "guest":
opts.Auth = nil // No authentication
opts.ReconnectAttempts = 3 // Fewer attempts for guests
default:
opts.Auth = map[string]interface{}{
"token": getUserToken(),
"role": "user",
}
}
return socketio.New("ws://localhost:3000", opts)
}
Configuration with Validation¶
func newClientWithValidation(url string, opts socketio.Options) (*socketio.Socket, error) {
// Validate options
if opts.ReconnectDelay > opts.ReconnectDelayMax {
return nil, fmt.Errorf("ReconnectDelay cannot be greater than ReconnectDelayMax")
}
if opts.Timeout < time.Second {
return nil, fmt.Errorf("Timeout must be at least 1 second")
}
if opts.AckTimeout < 100*time.Millisecond {
return nil, fmt.Errorf("AckTimeout too short")
}
return socketio.New(url, opts), nil
}
Configuration by Environment¶
func getOptions(env string) socketio.Options {
opts := socketio.Options{}
switch env {
case "development":
opts.Timeout = 60 * time.Second // Long timeouts for debugging
opts.AckTimeout = 30 * time.Second
opts.ReconnectAttempts = 10
case "staging":
opts.Timeout = 30 * time.Second
opts.AckTimeout = 10 * time.Second
opts.ReconnectAttempts = 5
case "production":
opts.Timeout = 20 * time.Second
opts.AckTimeout = 5 * time.Second
opts.ReconnectAttempts = 5
opts.Headers = map[string]string{
"X-Environment": "production",
}
default:
// Default values
opts.Timeout = 20 * time.Second
opts.ReconnectAttempts = 5
}
return opts
}
// Usage
client := socketio.New("ws://localhost:3000", getOptions(os.Getenv("ENV")))
Default Values¶
If no options are specified, these are the default values:
Options{
Auth: nil,
Headers: nil,
ReconnectAttempts: 5,
ReconnectDelay: 1 * time.Second,
ReconnectDelayMax: 5 * time.Second,
Timeout: 20 * time.Second,
AckTimeout: 5 * time.Second,
}
Best Practices¶
1. Adjust Timeouts Based on Network¶
// For mobile or unstable networks
opts := socketio.Options{
Timeout: 30 * time.Second, // Connection may take longer
AckTimeout: 10 * time.Second, // Responses may take longer
ReconnectDelay: 2 * time.Second, // Don't reconnect too quickly
}
2. Use Secure Authentication¶
// Always use tokens, never direct credentials
opts := socketio.Options{
Auth: map[string]interface{}{
"token": getSecureToken(), // JWT or similar
},
}
// Avoid this in production
opts := socketio.Options{
Auth: map[string]interface{}{
"username": "admin", // ❌ Insecure
"password": "1234", // ❌ Very insecure
},
}
3. Configure Reconnection Based on Use Case¶
// Critical application: many attempts
criticalApp := socketio.Options{
ReconnectAttempts: 20,
ReconnectDelayMax: 30 * time.Second,
}
// Temporary application: few attempts
temporaryApp := socketio.Options{
ReconnectAttempts: 3,
ReconnectDelayMax: 5 * time.Second,
}
4. Logging Configuration in Development¶
opts := socketio.Options{
ReconnectAttempts: 5,
Timeout: 30 * time.Second,
}
if os.Getenv("DEBUG") == "true" {
fmt.Printf("Socket.IO Options:\n")
fmt.Printf(" ReconnectAttempts: %d\n", opts.ReconnectAttempts)
fmt.Printf(" Timeout: %v\n", opts.Timeout)
fmt.Printf(" AckTimeout: %v\n", opts.AckTimeout)
}
client := socketio.New("ws://localhost:3000", opts)