Skip to content
Permalink
Browse files

play with Server-Sent Events with WebAssembly

  • Loading branch information...
dmitshur committed Sep 10, 2018
1 parent f2c533b commit 74ae464aa68c307f12094d6eae251a9f7b667ac5
Showing with 520 additions and 0 deletions.
  1. +18 −0 248/gopherjs/main.go
  2. +33 −0 248/sse.go
  3. +14 −0 248/wasm/index.html
  4. +17 −0 248/wasm/main.go
  5. +1 −0 248/wasm/run.sh
  6. +437 −0 248/wasm/wasm_exec.js
@@ -0,0 +1,18 @@
// +build js,!wasm

package main

import (
"fmt"

"github.com/gopherjs/eventsource"
"github.com/gopherjs/gopherjs/js"
)

func main() {
es := eventsource.New("http://localhost:8090/sse")
es.AddEventListener("message", false, func(event *js.Object) {
data := event.Get("data").String()
fmt.Println(data)
})
}
@@ -0,0 +1,33 @@
// +build ignore

package main

import (
"fmt"
"log"
"net/http"
"time"
)

func main() {
http.HandleFunc("/sse", func(w http.ResponseWriter, req *http.Request) {
if req.Method != "GET" && req.Method != "HEAD" {
w.Header().Set("Allow", "GET, HEAD")
http.Error(w, "405 Method Not Allowed\n\nmethod should be GET or HEAD", http.StatusMethodNotAllowed)
return
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Access-Control-Allow-Origin", "*")
f, ok := w.(http.Flusher)
if !ok {
log.Println("streaming unsupported")
http.Error(w, "streaming unsupported", http.StatusInternalServerError)
return
}
for now := range time.Tick(time.Second) {
fmt.Fprintf(w, "data: %s\n\n", now.Format("15:04:05"))
f.Flush()
}
})
log.Fatalln(http.ListenAndServe("localhost:8090", nil))
}
@@ -0,0 +1,14 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="wasm_exec.js"></script>
<script>
const go = new Go();
WebAssembly.instantiateStreaming(fetch("main.wasm"), go.importObject).then((result) => {
go.run(result.instance);
});
</script>
</head>
<body></body>
</html>
@@ -0,0 +1,17 @@
// +build js,wasm

package main

import (
"fmt"
"syscall/js"
)

func main() {
es := js.Global().Get("EventSource").New("http://localhost:8090/sse")
es.Call("addEventListener", "message", js.NewEventCallback(0, func(event js.Value) {
data := event.Get("data").String()
fmt.Println(data)
}))
select {}
}
@@ -0,0 +1 @@
GOOS=js GOARCH=wasm go build -o main.wasm && echo ok && goexec 'http.ListenAndServe(":8080", http.FileServer(http.Dir(".")))'

0 comments on commit 74ae464

Please sign in to comment.
You can’t perform that action at this time.