🚧 Add hello with state

This commit is contained in:
Nicolas Lepage
2021-01-22 15:54:33 +01:00
parent 07057523bf
commit a48b088723
5 changed files with 69 additions and 0 deletions

32
docs/hello-state/api.go Normal file
View File

@@ -0,0 +1,32 @@
package main
import (
"encoding/json"
"fmt"
"net/http"
wasmhttp "github.com/nlepage/go-wasm-http-server"
)
func main() {
var no = 1
http.HandleFunc("/hello", func(res http.ResponseWriter, req *http.Request) {
params := make(map[string]string)
if err := json.NewDecoder(req.Body).Decode(&params); err != nil {
panic(err)
}
if err := json.NewEncoder(res).Encode(map[string]string{
"message": fmt.Sprintf("Hello %s! (request n°%d)", params["name"], no),
}); err != nil {
panic(err)
}
no++
})
wasmhttp.Serve(nil)
select {}
}

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

Binary file not shown.

View File

@@ -0,0 +1,25 @@
<!DOCTYPE html>
<html>
<head>
<title>go-wasm-http-server hello with state demo</title>
<script>
navigator.serviceWorker.register('sw.js')
async function hello() {
res = await fetch('api/hello', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: document.querySelector("#name").value })
})
const { message } = await res.json()
alert(message)
}
</script>
</head>
<body>
<label for="name">Name: </label><input id="name" value="World">
<button onclick="hello()">Hello</button>
</body>
</html>

11
docs/hello-state/sw.js Normal file
View File

@@ -0,0 +1,11 @@
importScripts('https://cdn.jsdelivr.net/gh/nlepage/go-wasm-http-server@078ff3547ebe2abfbee1fd5af9ca5ad64be480c0/sw.js')
addEventListener('install', (event) => {
event.waitUntil(skipWaiting())
})
addEventListener('activate', event => {
event.waitUntil(clients.claim())
})
registerWasmHTTPListener('api.wasm', { base: 'api' })

View File

@@ -6,6 +6,7 @@
<body>
<ul>
<li><a href="hello">Hello demo</a></li>
<li><a href="hello-state">Hello with state demo</a></li>
</ul>
</body>
</html>