When I load the page in my browser, the page gets served correctly. When the javascript executes, Chrome's console output says:
Invalid UTF-8 sequence in header value
I have searched for that string, and am unable to find any mention of it for golang.
How do I go about telling golang not to write unicode characters to web sockets?
I assume that this is the cause of the problem, as the "Network" tab only reveals an empty request and response for this.
CCSSE:
main.go:
package main
import (
"fmt"
"net/http"
"log"
"code.google.com/p/go.net/websocket"
//"github.com/garyburd/go-websocket/websocket"
)
const listenAddress = "localhost:9999"
func wsHandler(webSck *websocket.Conn) {
fmt.Fprint(webSck, "Rpy")
fmt.Println("Sent \"Rpy\" to web socket", webSck)
//more code here
}
func main() {
http.Handle("/", http.FileServer(http.Dir("./static")))
http.Handle("/ws", websocket.Handler(wsHandler))
err := http.ListenAndServe(listenAddress, nil)
if err != nil {
log.Fatal(err)
}
}
static/main.js
var socket = new WebSocket("ws://localhost:9999/ws");
socket.onopen = function() {
socket.onmessage = function(m) {
console.log("Received: " + m);
};
socket.send("Req
");
};
EDIT:
As suggested by @Intermernet, I have set the Sec-WebSocket-Protocol
header. To no avail, still getting Invalid UTF-8 sequence in header value
.
Note also that the reason I need to do webSck.Config().Header = make(http.Header)
is that it is nil
- confirmed by the log statement on webSck.Config()
. Tack on to this another question - why do I have to do this; is there an intialisation step that I have missed somewhere?
func wsHandler(webSck *websocket.Conn) {
webSck.Config().Header = make(http.Header)
webSck.Config().Header.Add("Sec-WebSocket-Protocol", "chat")
fmt.Printf("ws.Config() %#v
", webSck.Config())
var buf []byte;
buf = []byte("Rpy")
_, err := webSck.Write(buf)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Printf("Sent \"Rpy\" to web socket %#v
", webSck)
}
}