Skip to content

Instantly share code, notes, and snippets.

@jordanorelli
Created January 1, 2012 18:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jordanorelli/1547943 to your computer and use it in GitHub Desktop.
Save jordanorelli/1547943 to your computer and use it in GitHub Desktop.
websockets in Go.
<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>
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)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment