How to Handle WebSocket Authentication in Go

Web
Implement WebSocket authentication in Go by validating credentials during the HTTP handshake before allowing the connection upgrade.

Go does not provide a built-in WebSocket authentication mechanism; you must implement it by validating a token or session during the HTTP handshake before upgrading the connection. Use the http package to inspect headers or cookies, verify credentials, and only then allow the WebSocket upgrade to proceed.

func authHandler(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        token := r.Header.Get("Authorization")
        if token == "" || !validateToken(token) {
            http.Error(w, "Unauthorized", http.StatusUnauthorized)
            return
        }
        next.ServeHTTP(w, r)
    })
}

func validateToken(token string) bool {
    // Replace with your actual validation logic
    return token == "valid-secret-token"
}

// Usage with a WebSocket library like gorilla/websocket
func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/ws", authHandler(http.HandlerFunc(wsHandler)).ServeHTTP)
    http.ListenAndServe(":8080", mux)
}