Skip to content

Instantly share code, notes, and snippets.

@husio
Created October 12, 2012 14:01
Show Gist options
  • Select an option

  • Save husio/3879320 to your computer and use it in GitHub Desktop.

Select an option

Save husio/3879320 to your computer and use it in GitHub Desktop.
Websocket proxy
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Websockproxy test</title>
<script type="text/javascript" charset="utf-8">
window.onload = function () {
var ws = new WebSocket('ws://' + document.location.host + '/ws');
ws.onopen = function (ev) {
};
ws.onclose = function (ev) {
};
ws.onmessage = function (ev) {
content.innerHTML = ev.data;
};
ws.onerror = function (ev) {
};
var input = document.getElementById("selector");
var contnt = document.getElementById("content");
input.onchange = function () {
if (!input.value) {
content.innerHTML = '';
} else {
ws.send(input.value + '\n');
}
}
};
</script>
</head>
<body>
URL: <input id="selector" type="search" style="width:600px">
<hr>
<div id="content"></div>
</body>
</html>
package main
import (
"bufio"
"code.google.com/p/go.net/websocket"
"fmt"
"io"
"io/ioutil"
"net/http"
)
func readWebsocket(ws *websocket.Conn) (chan string, chan error) {
cMessages := make(chan string, 32)
cErr := make(chan error)
go func() {
defer fmt.Println("Websocket reader closed")
r := bufio.NewReader(ws)
for {
msg, err := r.ReadBytes('\n')
if err != nil {
cErr <- err
return
}
cMessages <- string(msg[:len(msg)-1])
}
}()
return cMessages, cErr
}
func getPage(url string) []byte {
fmt.Printf("Get page: %s\n", url)
resp, err := http.Get(url)
if err != nil {
return []byte(err.Error())
}
content, err := ioutil.ReadAll(resp.Body)
if err != nil {
return []byte(err.Error())
}
return content
}
func clientHandler(ws *websocket.Conn) {
defer fmt.Println("Client disconnected")
wsmsg, wserr := readWebsocket(ws)
for {
select {
case msg := <-wsmsg:
ws.Write(getPage(msg))
case err := <-wserr:
if err == io.EOF {
return
}
panic(err)
}
}
}
func main() {
http.Handle("/", http.FileServer(http.Dir("/home/husio/websockproxy")))
http.Handle("/ws", websocket.Handler(clientHandler))
if err := http.ListenAndServe(":8080", nil); err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment