Skip to content

Instantly share code, notes, and snippets.

@willybeans
Last active February 9, 2024 15:47
Show Gist options
  • Save willybeans/c4be9c80c8d273b6f50123b546f9833e to your computer and use it in GitHub Desktop.
Save willybeans/c4be9c80c8d273b6f50123b546f9833e to your computer and use it in GitHub Desktop.
Connect gorilla websockets to chi router
package main
import (
"net/http"
"time"
"github.com/willybeans/freedu_go/handlers"
"github.com/willybeans/freedu_go/logger"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
)
func NewRouter() *chi.Mux {
router := chi.NewRouter()
// Middleware
router.Use(middleware.RequestID)
router.Use(middleware.RealIP)
router.Use(logger.RequestLogger)
router.Use(middleware.Timeout(60 * time.Second))
router.Get("/healthcheck", handlers.Healthcheck)
/*
using the gorilla websocket demo - https://github.com/gorilla/websocket/tree/main/examples/chat
import the files for client.go and hub.go into your project
then include this following code in your chi router file/function
Side Note: if you get an error `response does not implement http.Hijacker`:
it most likely has to do with a middleware you are using, and most likely isnt a problem with the demo or with chi
*/
hub := newHub()
go hub.run()
router.Handle("/ws", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
println("testing websockets!")
serveWs(hub, w, r)
}))
return router
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment