Files
fn_registry/functions/infra/ws_upgrader.go
T

37 lines
884 B
Go

package infra
import (
"fmt"
"net/http"
"nhooyr.io/websocket"
)
// WSUpgrader hace el upgrade de una conexion HTTP a WebSocket usando nhooyr.io/websocket.
// Si origins contiene "*" se acepta cualquier origen (InsecureSkipVerify=true).
// En caso contrario, OriginPatterns valida el header Origin del cliente con filepath.Match.
// Retorna el *websocket.Conn listo para Read/Write o un error si el handshake falla.
func WSUpgrader(w http.ResponseWriter, r *http.Request, origins []string) (*websocket.Conn, error) {
opts := &websocket.AcceptOptions{}
allowAny := false
for _, o := range origins {
if o == "*" {
allowAny = true
break
}
}
if allowAny {
opts.InsecureSkipVerify = true
} else {
opts.OriginPatterns = origins
}
conn, err := websocket.Accept(w, r, opts)
if err != nil {
return nil, fmt.Errorf("ws upgrade: %w", err)
}
return conn, nil
}