public
Created

websockets in Go.

  • Download Gist
index.html
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
<html>
<head>
<title>websockets</title>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>$(function() {
var conn;
conn = new WebSocket("ws://localhost:8000/echo");
conn.onopen = function(event) {
console.log("WebSocket Connected", event);
};
conn.onclose = function(event) {
console.log("WebSocket closed", event);
};
conn.onerror = function(event) {
console.log("WebSocket error", event);
};
conn.onmessage = function(event) {
console.log("Received:", event.data);
$("#responses").append("<li>" + event.data + "</li>");
};
 
$("#requests").keydown(function(event) {
if(event.keyCode == 13){
var text = $.trim($("#requests").val());
if(text){
conn.send(text);
$("#requests").val("");
}
}
});
});</script>
</head>
<body>
<ul id="responses"></ul>
<input id="requests" type="text" />
</body>
</html>
main.go
Go
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
package main
 
import (
"http"
"io"
"websocket"
)
 
func Home(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "./index.html")
}
 
func Echo(ws *websocket.Conn) {
io.Copy(ws, ws)
}
 
func main() {
port := "0.0.0.0:8000"
http.HandleFunc("/", Home)
http.Handle("/echo", websocket.Handler(Echo))
http.ListenAndServe(port, nil)
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.