Skip to content

Instantly share code, notes, and snippets.

@tab1293
Created February 20, 2017 17:46
Show Gist options
  • Save tab1293/1b8aa5f0cbddee793610dd0a1da80ebe to your computer and use it in GitHub Desktop.
Save tab1293/1b8aa5f0cbddee793610dd0a1da80ebe to your computer and use it in GitHub Desktop.
websocket file reader
<html>
<head></head>
<body>
<form action="/file" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
<script>
var ws;
var fileInput = document.getElementById("file");
var input = document.getElementById("input");
fileInput.onchange = function(e) {
ws = new WebSocket("ws://localhost:8080/file");
var file = e.target.files[0]
console.log(file)
ws.onopen = function(evt) {
console.log("OPEN");
}
ws.onclose = function(evt) {
console.log("CLOSE");
ws = null;
}
ws.onmessage = function(evt) {
console.log("msg: " + evt.data);
var msg = JSON.parse(evt.data);
var slice = file.slice(msg.Offset, 32)
var reader = new window.FileReader();
reader.readAsDataURL(slice);
reader.onloadend = function() {
base64data = reader.result;
console.log(base64data);
ws.send(JSON.stringify({ID: 'test', Data: base64data}));
}
}
ws.onerror = function(evt) {
console.log("ERROR: " + evt.data);
}
}
</script>
</html>
package main
import (
"strings"
"log"
"net/http"
"github.com/gorilla/websocket"
"encoding/base64"
"fmt"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
type DataMsg struct {
ID string
Data string
}
type ReadMsg struct {
Offset int64
}
type SocketFile struct {
Conn *websocket.Conn
DataChan chan []byte
Offset int64
}
type SocketFileHub struct {
Hub map[string]*SocketFile
}
func (sf *SocketFile) Handle() error {
for {
v := &DataMsg{}
err := sf.Conn.ReadJSON(v)
if err != nil {
fmt.Println("err on reading json")
panic(err)
}
v.Data = strings.TrimPrefix(v.Data, "data:;base64,")
p, err := base64.StdEncoding.DecodeString(v.Data)
if err != nil {
fmt.Println("err base64")
panic(err)
}
sf.DataChan <- p
}
return nil
}
func (sf *SocketFile) Read(p []byte) (n int, err error) {
msg := &ReadMsg{
Offset: sf.Offset,
}
sf.Conn.WriteJSON(msg)
select {
case data := <-sf.DataChan:
p = make([]byte, len(data))
copy(p, data)
}
fmt.Printf("%x\n", p)
return len(p), nil
}
func WebsocketFileHandler(w http.ResponseWriter, r *http.Request, hub *SocketFileHub) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
sf := &SocketFile {
Conn: conn,
DataChan: make(chan []byte),
Offset: 0,
}
hub.Hub["test"] = sf
go sf.Handle()
}
func FileRequestHandler(w http.ResponseWriter, r *http.Request, hub *SocketFileHub) {
sf := hub.Hub["test"]
p := make([]byte, 32)
n, err := sf.Read(p)
if err != nil {
return
}
fmt.Printf("%x", p)
fmt.Fprintf(w, "Hello, %d %x", n, p)
}
func main() {
hub := &SocketFileHub {
Hub: make(map[string]*SocketFile),
}
http.HandleFunc("/file", func(w http.ResponseWriter, r *http.Request) {
WebsocketFileHandler(w, r, hub)
})
http.HandleFunc("/stream", func(w http.ResponseWriter, r *http.Request) {
FileRequestHandler(w, r, hub)
})
http.Handle("/", http.FileServer(http.Dir("/Users/tom/go/src/github.com/tab1293/test")))
http.ListenAndServe(":8080", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment