go-chi / chi

lightweight, idiomatic and composable router for building Go HTTP services
https://go-chi.io
MIT License
18.24k stars 980 forks source link

How can I use SockJS-go with Chi? #146

Closed kvnxiao closed 7 years ago

kvnxiao commented 7 years ago

Hey there,

I was wondering how I could use sockjs-go with Chi. I'm writing a real-time web game application for one of my projects so I was thinking of using sockjs as a websocket implementation.

Of course, running the example code for sockjs-go using net/http is no problem, but when I try to set the sockjs-go handler for a chi router, I end up with a 304 followed by a 404 for sockjs info. I'm kind of new to this so I am not sure if I am doing something wrong, but what I am doing is as follows:

func main() {
    r := chi.NewRouter()
    r.Use(middleware.RequestID)
    r.Use(middleware.RealIP)
    r.Use(middleware.Logger)
    r.Use(middleware.Recoverer)

    handler := sockjs.NewHandler("/echo", sockjs.DefaultOptions, func(session sockjs.Session) {
        for {
            if msg, err := session.Recv(); err == nil {
                if session.Send(msg) != nil {
                    break
                }
            } else {
                break
            }
        }
    })

    r.FileServer("/", http.Dir("web/"))
    r.Handle("/echo/", handler)
    http.ListenAndServe(":3000", r)
}

I am simply trying to run an echo example to send message from client to server and back, but I cannot seem to get the client to connect to the server through websocket.

zet4 commented 7 years ago

Note: I haven't tested this

Try using r.Mount("/echo", sockjs.NewHandler("/", ...)), I would however suggest using https://github.com/olahol/melody with normal WS connection on client side, instead of sockjs.

kvnxiao commented 7 years ago

@zet4 Thanks! using Mount() worked with the echo example.

Regarding your suggestion to use normal WS connection, is there a big reason people prefer a normal WS connection over polyfills like socket.io and sockjs?

And how does melody compare with gorilla websockets?

pkieltyka commented 7 years ago

thanks for answering the question @zet4 - I'm going to close this since question is answered

zet4 commented 7 years ago

@alphahelix00 the issue is closed but I guess I will still answer your question, socket.io/sockjs add additional overhead/costs on top of normal WS (if its even using WS, it might fallback to Polling without you knowing)

Melody is still using gorilla websockets underneath, its just a nicer wrapper with session handling added. I use it for one of my person projects alongside Chi.

curtismenmuir commented 8 months ago

@zet4 thanks for the update, do you have any example code for getting getting this working with melody?