zishang520 / socket.io

socket.io for golang, Start your pleasant journey! Support Socket.IO v4+😀
MIT License
281 stars 19 forks source link

How to create a client on the server? #60

Closed bneigher closed 4 months ago

bneigher commented 4 months ago

I am trying to write some tests here (specifically for middleware SocketIOMiddleware, and am wondering how exactly one would set up a client and use that client on the server?

Here is what I've been trying to do:

package middleware

import (
    "net/http"
    "net/http/httptest"
    "testing"

    "github.com/gin-gonic/gin"
    "github.com/stretchr/testify/assert"
)

func TestSocketIOMiddleware(t *testing.T) {
    tests := []struct {
        name       string
        auth       map[string]interface{}
        shouldPass bool
    }{
        {
            name: "Valid cookie auth",
            auth: map[string]interface{}{
                "cookie": "session=good",
            },
            shouldPass: true,
        },
        {
            name: "Invalid cookie auth",
            auth: map[string]interface{}{
                "cookie": "session=bad;",
            },
            shouldPass: false,
        },
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            socketio := socket.NewServer(nil, nil)
            socketio.Of(regexp.MustCompile(`/\w+`), nil).
                Use(SocketIOMiddleware()).
                On("connection", func(clients ...interface{}) {
                    client := clients[0].(*socket.Socket)
                    client.Handshake().Auth = tt.auth
                })

            client := socket.NewClient(socketio, nil)
            client.Conn().Emit("ping")

            // Perform assertions based on the middleware behavior
            if tt.shouldPass {
                assert.True(t, true, "Expected middleware to pass")
            } else {
                assert.False(t, false, "Expected middleware to fail")
            }
        })
    }
}

I'm getting a panic because I don't know what to pass in to NewClient conn argument

zishang520 commented 4 months ago

Sorry, currently only the golang version of socket.io server is available, the golang version of socket.io client is not ready yet.

zishang520 commented 4 months ago

The Client struct in this version library is the client connection session information in the server.

bneigher commented 4 months ago

ohhh. makes sense, ok thanks