The title is basically the question I have. I was developing my Go server, and added the gorilla/ws library to the endpoint http://qwerty:1234/api/ws to handle connection upgrade requests.
This endpoint has a middleware before it that validates the Auth header's bearer token.
While developing I could customize the WS connection request in Postman to include the Auth header. And it successfully connected to the WS endpoint.
I'm new to WS. And I tried to develop the client side WS connection, lo, you can't add headers.
Is there a workaround to do what I am trying? Or is there a way to emulate what Postman does? Is there a Javascript WS library that I can use to do what I am trying?
Server code
// Router
r.Route("/api", func(r chi.Router) {
r.Group(func(r chi.Router) {
r.Use(utils.AuthMiddleware)
r.Get("/contacts", controller.GetContacts)
r.Get("/ws", websocket.Handler)
r.Get("/ws/clients", websocket.TestHandler)
// Socket connection upgrade
func Handler(w http.ResponseWriter, r *http.Request) {
userDetails := r.Context().Value("userDetails").(jwt.MapClaims) // Populated by middleware
userId := int64(userDetails["UserId"].(float64))
if _, userPresent := wsClientsById[userId]; userPresent {
http.Error(w, "User already connected", http.StatusForbidden)
return
}
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
http.Error(w, "Error establishing Websocket connection", http.StatusInternalServerError)
fmt.Println(err)
return
}
conn.SetReadLimit(4096)
wsClientsById[userId] = conn
wsClientsByConn[conn] = userId
go wsConnHandler(conn)
}