Options API Reference¶
El tipo Options permite configurar el comportamiento del cliente Socket.IO.
Tabla de Contenidos¶
- Definición
- Opciones de Autenticación
- Opciones de Conexión
- Opciones de Reconexión
- Opciones de Timeouts
- Ejemplos
Definición¶
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
}
Todas las opciones son opcionales. Si no se especifican, se usan valores por defecto razonables.
Opciones de Autenticación¶
Auth¶
Datos de autenticación enviados durante el handshake inicial. Útil para tokens JWT, credenciales, etc.
Tipo: map[string]interface{} Valor por defecto: nil (sin autenticación)
Ejemplo:
client := socketio.New("ws://localhost:3000", socketio.Options{
Auth: map[string]interface{}{
"token": "eyJhbGciOiJIUzI1NiIs...",
},
})
Ejemplo con JWT:
client := socketio.New("ws://localhost:3000", socketio.Options{
Auth: map[string]interface{}{
"token": jwtToken,
"userId": "user-123",
},
})
Ejemplo con credenciales:
client := socketio.New("ws://localhost:3000", socketio.Options{
Auth: map[string]interface{}{
"username": "juan",
"password": "secreto",
},
})
Headers¶
Headers HTTP personalizados enviados durante la conexión inicial.
Tipo: map[string]string Valor por defecto: nil (sin headers personalizados)
Ejemplo:
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",
},
})
Opciones de Reconexión¶
ReconnectAttempts¶
Número máximo de intentos de reconexión antes de rendirse.
Tipo: int Valor por defecto: 5 Valor especial: -1 = intentos infinitos
Ejemplo:
// 10 intentos de reconexión
client := socketio.New("ws://localhost:3000", socketio.Options{
ReconnectAttempts: 10,
})
// Intentos infinitos (usar con precaución)
client := socketio.New("ws://localhost:3000", socketio.Options{
ReconnectAttempts: -1,
})
// Sin reconexión automática
client := socketio.New("ws://localhost:3000", socketio.Options{
ReconnectAttempts: 0,
})
ReconnectDelay¶
Tiempo de espera inicial antes del primer intento de reconexión. Este valor se incrementa exponencialmente en cada intento.
Tipo: time.Duration Valor por defecto: 1 * time.Second
Ejemplo:
// Esperar 2 segundos antes del primer intento
client := socketio.New("ws://localhost:3000", socketio.Options{
ReconnectDelay: 2 * time.Second,
})
// Reconexión rápida (500ms)
client := socketio.New("ws://localhost:3000", socketio.Options{
ReconnectDelay: 500 * time.Millisecond,
})
ReconnectDelayMax¶
Tiempo máximo de espera entre intentos de reconexión. El backoff exponencial no excederá este valor.
Tipo: time.Duration Valor por defecto: 5 * time.Second
Ejemplo:
// Limitar el delay máximo a 10 segundos
client := socketio.New("ws://localhost:3000", socketio.Options{
ReconnectDelay: time.Second,
ReconnectDelayMax: 10 * time.Second,
})
Comportamiento del backoff exponencial:
// Con ReconnectDelay = 1s y ReconnectDelayMax = 5s:
// Intento 1: espera 1s
// Intento 2: espera 2s
// Intento 3: espera 4s
// Intento 4: espera 5s (limitado por ReconnectDelayMax)
// Intento 5: espera 5s
Opciones de Timeouts¶
Timeout¶
Timeout para establecer la conexión inicial.
Tipo: time.Duration Valor por defecto: 20 * time.Second
Ejemplo:
// Timeout de 30 segundos para conexión lenta
client := socketio.New("ws://localhost:3000", socketio.Options{
Timeout: 30 * time.Second,
})
// Timeout corto para fallar rápido (5 segundos)
client := socketio.New("ws://localhost:3000", socketio.Options{
Timeout: 5 * time.Second,
})
AckTimeout¶
Timeout global para esperar acknowledgments. Si el servidor no responde dentro de este tiempo, el callback de acknowledgment recibe nil.
Tipo: time.Duration Valor por defecto: 5 * time.Second
Ejemplo:
// Timeout de 10 segundos para operaciones lentas
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: operación tardó más de 10 segundos")
return
}
fmt.Println("Respuesta:", response[0])
}, "datos")
Opciones de Conexión¶
Path¶
Nota: Esta opción no está implementada en el struct actual, pero se puede agregar en el futuro.
El path del endpoint Socket.IO en el servidor.
Valor por defecto: /socket.io/
Ejemplos¶
Configuración Básica¶
client := socketio.New("ws://localhost:3000", socketio.Options{
ReconnectAttempts: 5,
Timeout: 30 * time.Second,
})
Configuración con Autenticación¶
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",
},
})
Configuración para Reconexión Agresiva¶
client := socketio.New("ws://localhost:3000", socketio.Options{
ReconnectAttempts: 10,
ReconnectDelay: 500 * time.Millisecond, // Intentar rápido
ReconnectDelayMax: 3 * time.Second, // Pero no esperar mucho
})
Configuración para Conexiones Lentas¶
client := socketio.New("ws://slow-server.example.com", socketio.Options{
Timeout: 60 * time.Second, // Timeout largo para conexión
AckTimeout: 30 * time.Second, // Timeout largo para respuestas
})
Configuración Sin Reconexión¶
// Para casos donde no quieres reconexión automática
client := socketio.New("ws://localhost:3000", socketio.Options{
ReconnectAttempts: 0, // Desactivar reconexión
})
client.OnDisconnect(func(reason string) {
fmt.Println("Desconectado, sin intentos de reconexión")
// Implementar lógica personalizada aquí
})
Configuración Completa¶
client := socketio.New("wss://api.example.com", socketio.Options{
// Autenticación
Auth: map[string]interface{}{
"token": getAuthToken(),
"userId": getCurrentUserId(),
"deviceId": getDeviceId(),
},
// Headers personalizados
Headers: map[string]string{
"Authorization": "Bearer " + getJWT(),
"X-API-Key": "api-key-123",
"X-Client-Version": "1.0.0",
},
// Reconexión configurada
ReconnectAttempts: 10,
ReconnectDelay: time.Second,
ReconnectDelayMax: 5 * time.Second,
// Timeouts configurados
Timeout: 30 * time.Second,
AckTimeout: 10 * time.Second,
})
Configuración Dinámica¶
func createClient(userType string) *socketio.Socket {
opts := socketio.Options{
ReconnectAttempts: 5,
Timeout: 20 * time.Second,
}
// Configuración específica por tipo de usuario
switch userType {
case "admin":
opts.Auth = map[string]interface{}{
"token": getAdminToken(),
"role": "admin",
}
opts.ReconnectAttempts = 10 // Más intentos para admins
case "guest":
opts.Auth = nil // Sin autenticación
opts.ReconnectAttempts = 3 // Menos intentos para invitados
default:
opts.Auth = map[string]interface{}{
"token": getUserToken(),
"role": "user",
}
}
return socketio.New("ws://localhost:3000", opts)
}
Configuración con Validación¶
func newClientWithValidation(url string, opts socketio.Options) (*socketio.Socket, error) {
// Validar opciones
if opts.ReconnectDelay > opts.ReconnectDelayMax {
return nil, fmt.Errorf("ReconnectDelay no puede ser mayor que ReconnectDelayMax")
}
if opts.Timeout < time.Second {
return nil, fmt.Errorf("Timeout debe ser al menos 1 segundo")
}
if opts.AckTimeout < 100*time.Millisecond {
return nil, fmt.Errorf("AckTimeout muy corto")
}
return socketio.New(url, opts), nil
}
Configuración por Entorno¶
func getOptions(env string) socketio.Options {
opts := socketio.Options{}
switch env {
case "development":
opts.Timeout = 60 * time.Second // Timeouts largos para 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:
// Valores por defecto
opts.Timeout = 20 * time.Second
opts.ReconnectAttempts = 5
}
return opts
}
// Uso
client := socketio.New("ws://localhost:3000", getOptions(os.Getenv("ENV")))
Valores por Defecto¶
Si no se especifica ninguna opción, estos son los valores por defecto:
Options{
Auth: nil,
Headers: nil,
ReconnectAttempts: 5,
ReconnectDelay: 1 * time.Second,
ReconnectDelayMax: 5 * time.Second,
Timeout: 20 * time.Second,
AckTimeout: 5 * time.Second,
}
Mejores Prácticas¶
1. Ajustar Timeouts según la Red¶
// Para redes móviles o inestables
opts := socketio.Options{
Timeout: 30 * time.Second, // Conexión puede tardar
AckTimeout: 10 * time.Second, // Respuestas pueden tardar
ReconnectDelay: 2 * time.Second, // No reconectar demasiado rápido
}
2. Usar Autenticación Segura¶
// Siempre usar tokens, nunca credenciales directas
opts := socketio.Options{
Auth: map[string]interface{}{
"token": getSecureToken(), // JWT o similar
},
}
// Evitar esto en producción
opts := socketio.Options{
Auth: map[string]interface{}{
"username": "admin", // ❌ Inseguro
"password": "1234", // ❌ Muy inseguro
},
}
3. Configurar Reconexión según el Caso de Uso¶
// Aplicación crítica: muchos intentos
criticalApp := socketio.Options{
ReconnectAttempts: 20,
ReconnectDelayMax: 30 * time.Second,
}
// Aplicación temporal: pocos intentos
temporaryApp := socketio.Options{
ReconnectAttempts: 3,
ReconnectDelayMax: 5 * time.Second,
}
4. Logging de Configuración en 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)