I am trying to post messages using Golang websocket and listen on Node client side.
Here's part of code:
Golang:
func NewUpgrader() *websocket.Upgrader {
return &websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
func (s WebsocketHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
upgrader := NewUpgrader()
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Errorf("websocket: could not upgrade %v", err)
fmt.Fprintf(w, "websocket: could not upgrade %v", err)
return
}
go func() {
defer ws.Close()
for msg := range s.Messages {
json, _ := json.Marshal(msg)
err := ws.WriteMessage(1, json)
if err != nil {
log.Errorf("websocket: error sending message: %v", err)
}
}
}()
By doing this I can get all the messages when I run the code below on Google console
ws = new WebSocket('ws://localhost:8080/ws')
ws.onmessage = function(msg) { console.log(JSON.parse(msg.data)) }
And I add the same two lines code on my client side, now I got these errors
Golang side:
INFO[0009] 400 GET localhost:8080/ws (0 bytes) id: 77b7355412f2ffcd
ERRO[0009] websocket: could not upgrade websocket: not a websocket handshake: 'upgrade' token not found in 'Connection' header
Client side(browser console):
GET http://localhost:8080/ws 400 (Bad Request)
Failed to load http://localhost:8080/ws: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4000' is therefore not allowed access. The response had HTTP status code 400. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Uncaught (in promise) TypeError: Failed to fetch
I tried to compare these two get request(Google console vs my client-side code). I found out that for google console there's a header Connection:[Upgrade]
, but the header looks like this Connection:[keep-alive]
in my client-side code.
Not sure if this is the reason why I can not connect these two, any ideas?
Thanks!