Golang Websocket Interact: error: Invalid WebSocket frame: RSV2 and RSV3 must be clear

100 Views Asked by At

When i am trying to connect through websocket, i am getting this error - Invalid WebSocket frame: RSV2 and RSV3 must be clear using wscat. When i used HTML which is provided bellow, it give error in golang log - exit status 1. Not sure why this is happening? Any solution on this? Go code gets build with no error and suggestions.

r.HandleFunc("/ws/pod-shell/{namespace_name}/{pod_name}/{container_name}", PodShellHandler)
import (
    "fmt"
    "os/exec"
    "net/http"
    config "kubethor-backend/config"
    "github.com/gorilla/websocket"
    "os"
    "github.com/gorilla/mux"
)

func StartPodShell(namespace, podName, containerName string, conn *websocket.Conn) error {
    // Get the path to the Kubernetes configuration file from the environment variable.
    kubeconfigPath := os.Getenv("KUBECONFIG")

    // Command to execute a shell in the specified container using the specified kubeconfig file and namespace.
    cmd := exec.Command("kubectl", "--kubeconfig", kubeconfigPath, "exec", "-it", "-n", namespace, podName, "-c", containerName, "--", "/bin/sh")

    cmd.Stdin = conn.UnderlyingConn()
    cmd.Stdout = conn.UnderlyingConn()
    cmd.Stderr = conn.UnderlyingConn()

    if err := cmd.Run(); err != nil {
        return err
    }

    return nil
}

func PodShellHandler(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    namespaceName := vars["namespace_name"]
    podName := vars["pod_name"]
    containerName := vars["container_name"]

    if namespaceName == "" || podName == "" || containerName == "" {
        http.Error(w, "Namespace, Pod Name and Pod Container Name must be provided", http.StatusBadRequest)
        return
    }

    // WebSocket Upgrader configuration
    // WebSocketUpgrader = websocket.Upgrader{
    //     ReadBufferSize:  1024,
    //     WriteBufferSize: 1024,
    //     CheckOrigin: func(r *http.Request) bool {
    //         // Implement your CORS policy here
    //         return true // For example, allow connections from any origin
    //     },
    // }
    conn, err := config.WebSocketUpgrader.Upgrade(w, r, nil)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer conn.Close()

    if err := StartPodShell(namespaceName, podName, containerName, conn); err != nil {
        fmt.Println(err)
    }
}

<!DOCTYPE html>
<html>

<head>
    <title>Pod Shell</title>
</head>

<body>
    <h1>Pod Shell</h1>

    <div>
        <label for="namespace">Namespace:</label>
        <input type="text" id="namespace" placeholder="Namespace">
    </div>

    <div>
        <label for="pod">Pod Name:</label>
        <input type="text" id="pod" placeholder="Pod Name">
    </div>

    <div>
        <label for="container">Container Name:</label>
        <input type="text" id="container" placeholder="Container Name">
    </div>

    <button onclick="connectToPodShell()">Connect</button>

    <div>
        <h2>Shell Output:</h2>
        <pre id="shell-output"></pre>
    </div>

    <script>
        let ws;
        const shellOutput = document.getElementById('shell-output');

        function connectToPodShell() {
            const namespace = document.getElementById('namespace').value;
            const podName = document.getElementById('pod').value;
            const containerName = document.getElementById('container').value;

            // Establish WebSocket connection with the server's /pod-shell endpoint.
            ws = new WebSocket(`ws://localhost:8080/ws/pod-shell/${namespace}/${podName}/${containerName}`);

            ws.onmessage = function (event) {
                // Display the received shell output.
                shellOutput.innerText += event.data + '\n';
            };

            ws.onclose = function () {
                // WebSocket connection closed.
                console.log('WebSocket closed.');
            };

            ws.onerror = function (error) {
                // WebSocket error.
                console.error('WebSocket error:', error);
            };
        }

        function disconnectFromPodShell() {
            // Close the WebSocket connection.
            if (ws) {
                ws.close();
            }
        }
    </script>
</body>

</html>

I want to interact with Pod Shell using Websocket in HTML. I tried with wscat library still same issue

0

There are 0 best solutions below