[FEATURE] Use ReadableStream for Response (#15)

* feat: uses ReadableStream for Response

* chore: rebuilds other examples
This commit is contained in:
Nicolas Lepage
2024-10-14 09:14:50 +02:00
committed by GitHub
parent 163b49702b
commit 5ec4a8d7e8
21 changed files with 644 additions and 93 deletions

34
docs/hello-sse/api.go Normal file
View File

@@ -0,0 +1,34 @@
package main
import (
"net/http"
"time"
"github.com/tmaxmax/go-sse"
wasmhttp "github.com/nlepage/go-wasm-http-server"
)
func main() {
s := &sse.Server{}
t, _ := sse.NewType("ping")
go func() {
m := &sse.Message{
Type: t,
}
m.AppendData("Hello world")
for range time.Tick(time.Second) {
_ = s.Publish(m)
}
}()
http.Handle("/events", s)
if _, err := wasmhttp.Serve(nil); err != nil {
panic(err)
}
select {}
}

BIN
docs/hello-sse/api.wasm Executable file

Binary file not shown.

32
docs/hello-sse/index.html Normal file
View File

@@ -0,0 +1,32 @@
<!DOCTYPE html>
<html>
<head>
<title>go-wasm-http-server hello demo</title>
<script>
navigator.serviceWorker.register('sw.js')
.then(registration => {
const serviceWorker = registration.installing ?? registration.waiting ?? registration.active
if (serviceWorker.state === 'activated') {
startEventSource()
} else {
serviceWorker.addEventListener('statechange', e => {
if (e.target.state === 'activated') startEventSource()
})
}
})
function startEventSource() {
const es = new EventSource('/api/events')
es.addEventListener('ping', (e) => {
const p = document.createElement('p')
p.textContent = `ping: data=${e.data}`
document.body.append(p)
})
window.addEventListener('unload', () => {
es.close()
})
}
</script>
</head>
<body></body>
</html>

12
docs/hello-sse/sw.js Normal file
View File

@@ -0,0 +1,12 @@
importScripts('https://cdn.jsdelivr.net/gh/golang/go@go1.23.1/misc/wasm/wasm_exec.js')
importScripts('https://cdn.jsdelivr.net/gh/nlepage/go-wasm-http-server@v1.1.0/sw.js')
addEventListener('install', (event) => {
event.waitUntil(skipWaiting())
})
addEventListener('activate', event => {
event.waitUntil(clients.claim())
})
registerWasmHTTPListener('api.wasm', { base: 'api' })

Binary file not shown.

View File

@@ -1,4 +1,4 @@
importScripts('https://cdn.jsdelivr.net/gh/golang/go@go1.18.4/misc/wasm/wasm_exec.js')
importScripts('https://cdn.jsdelivr.net/gh/golang/go@go1.23.1/misc/wasm/wasm_exec.js')
importScripts('https://cdn.jsdelivr.net/gh/nlepage/go-wasm-http-server@v1.1.0/sw.js')
addEventListener('install', (event) => {

Binary file not shown.

View File

@@ -1,4 +1,4 @@
importScripts('https://cdn.jsdelivr.net/gh/golang/go@go1.18.4/misc/wasm/wasm_exec.js')
importScripts('https://cdn.jsdelivr.net/gh/golang/go@go1.23.1/misc/wasm/wasm_exec.js')
importScripts('https://cdn.jsdelivr.net/gh/nlepage/go-wasm-http-server@v1.1.0/sw.js')
addEventListener('install', (event) => {