njones / socketio

A Modern SocketIO library for go
MIT License
64 stars 9 forks source link

Private callback does not allow me to create interfaces #50

Closed mutefiRe closed 9 months ago

mutefiRe commented 1 year ago

Hi! I'm currently trying to swap out go-socket.io with your library (because of the v4 compatibility), but I have problems due to the private structs and private callback typings.

When I want to create an interface for a Namespace / sio.inSocketV4 that's impossible, because I cannot make an On Method definition conforming to the private eventCallback interface definition, even if it matches the signature.

So I would propose to either expose interfaces (probably eventCallback would be good enough) to public or to not return private structs which can't be even embedded in self-defined data types. But maybe there is already a solution to this which I didn't see yet.

njones commented 1 year ago

Can you describe your use case in a little more detail. I think I have a fix, but I want to see if it should be applied in other places as well, based in part by your use case.

ethanholz commented 1 year ago

I am also experiencing this issue. For example, I want to write a handler for an event named myEvent. It appears that I would just write something like this

type myItem string

func (i myItem) Callback(...interface{}) error {
  return nil
}

func main() {
  var item myItem
  server := socketio.NewServer()
  server.On("myEvent", myItem.Callback)
}

I have a feeling that this is incorrect. How would I go about creating a callback for a custom event?

njones commented 1 year ago

https://github.com/njones/socketio/blob/main/callback/callback_test.go#L128-L139

type CustomWrap func(string, string) error

func (cc CustomWrap) Callback(data ...interface{}) error {
    a, aOK := data[0].(string)
    b, bOK := data[1].(string)

    if !aOK || !bOK {
        return fmt.Errorf("bad parameters")
    }

    return cc(a, b)
}

func main() {
    server := socketio.NewServer()
    server.OnConnect(func(socket *sio.SocketV4) error {
         socket.On("myEvent", CustomWrap(func(a string, b string) error{
            fmt.Println("a: %s, b: %s", a, b)
            return nil
         })
    }
}

Does this show you what you want to know? If so, there are more examples in that file.

ethanholz commented 1 year ago

@njones thanks for the quick reply, that looks more in line with what I expected . I will take a look and report back! Thank you!

ethanholz commented 1 year ago

Thank you, this seems to be working for me! I am open to creating a PR to include this in the README as subscription custom events is a common use-case of socket.io. @njones do you have a preference of how that should look?

njones commented 1 year ago

I think something like the example above would be ok. I would put it in it's own header and code block. It would be awesome to review your Pull Request.