wasm-http-server/README.md

239 lines
9.7 KiB
Markdown
Raw Normal View History

2019-11-26 23:22:12 +01:00
<h1 align="center">Welcome to go-wasm-http-server 👋</h1>
<p>
2021-01-24 21:28:56 +01:00
<a href="https://pkg.go.dev/github.com/nlepage/go-wasm-http-server#section-documentation">
<img src="https://pkg.go.dev/badge/github.com/nlepage/go-wasm-http-server.svg" alt="Go Reference">
2019-11-26 23:22:12 +01:00
</a>
<a href="https://github.com/nlepage/go-wasm-http-server/blob/master/LICENSE" target="_blank">
<img alt="License: Apache 2.0" src="https://img.shields.io/badge/License-Apache--2.0-yellow.svg" />
</a>
</p>
2021-02-18 22:01:34 +01:00
> Embed your Go HTTP handlers in a ServiceWorker (using [WebAssembly](https://mdn.io/WebAssembly/)) and emulate an HTTP server!
2019-11-26 23:22:12 +01:00
2021-01-31 21:59:22 +01:00
## Examples
- [Hello example](https://nlepage.github.io/go-wasm-http-server/hello) ([sources](https://github.com/nlepage/go-wasm-http-server/tree/master/docs/hello))
- [Hello example with state](https://nlepage.github.io/go-wasm-http-server/hello-state) ([sources](https://github.com/nlepage/go-wasm-http-server/tree/master/docs/hello-state))
- [Hello example with state and keepalive](https://nlepage.github.io/go-wasm-http-server/hello-state-keepalive) ([sources](https://github.com/nlepage/go-wasm-http-server/tree/master/docs/hello-state-keepalive))
- [Hello example with Server Sent Events](https://nlepage.github.io/go-wasm-http-server/hello-sse/) ([sources](https://nlepage.github.io/go-wasm-http-server/hello-sse/))
2021-01-31 21:59:22 +01:00
- [😺 Catption generator example](https://nlepage.github.io/catption/wasm) ([sources](https://github.com/nlepage/catption/tree/wasm))
- [Random password generator web server](https://nlepage.github.io/random-password-please/) ([sources](https://github.com/nlepage/random-password-please) forked from [jbarham/random-password-please](https://github.com/jbarham/random-password-please))
2025-01-19 11:15:30 +01:00
- [Server fallbacks, and compiling with TinyGo](https://nlepage.github.io/go-wasm-http-server/tinygo/) (runs locally; see [sources & readme](https://github.com/nlepage/go-wasm-http-server/tree/master/docs/tinygo#readme) for how to run this example)
2019-11-26 23:22:12 +01:00
2021-02-09 23:18:59 +01:00
## How?
Talk given at the Go devroom of FOSDEM 2021 explaining how `go-wasm-http-server` works:
2021-02-09 23:20:40 +01:00
[![Deploy a Go HTTP server in your browser Youtube link](https://raw.githubusercontent.com/nlepage/go-wasm-http-talk/main/youtube.png)](https://youtu.be/O2RB_8ircdE)
2021-02-09 23:18:59 +01:00
The slides are available [here](https://nlepage.github.io/go-wasm-http-talk/).
## Why?
`go-wasm-http-server` can help you put up a demonstration for a project without actually running a Go HTTP server.
2021-01-28 16:00:27 +01:00
## Requirements
2019-11-26 23:22:12 +01:00
2021-01-28 16:00:27 +01:00
`go-wasm-http-server` requires you to build your Go application to WebAssembly, so you need to make sure your code is compatible:
- no C bindings
- no System dependencies such as file system or network (database server for example)
- For smaller WASM blobs, your code may also benefit from being compatible with, and compiled by, [TinyGo](https://tinygo.org/docs/reference/lang-support/stdlib/). See the TinyGo specific details below.
2019-11-26 23:22:12 +01:00
## Usage
2021-01-28 16:00:27 +01:00
### Step 1: Build to `js/wasm`
In your Go code, replace [`http.ListenAndServe()`](https://pkg.go.dev/net/http#ListenAndServe) (or [`net.Listen()`](https://pkg.go.dev/net#Listen) + [`http.Serve()`](https://pkg.go.dev/net/http#Serve)) by [wasmhttp.Serve()](https://pkg.go.dev/github.com/nlepage/go-wasm-http-server#Serve):
📄 `server.go`
```go
// +build !js,!wasm
package main
import (
"net/http"
)
func main() {
// Define handlers...
http.ListenAndServe(":8080", nil)
}
```
becomes:
📄 `server_js_wasm.go`
```go
// +build js,wasm
package main
import (
2024-10-14 22:24:46 +02:00
wasmhttp "github.com/nlepage/go-wasm-http-server/v2"
2021-01-28 16:00:27 +01:00
)
func main() {
// Define handlers...
wasmhttp.Serve(nil)
}
```
You may want to use build tags as shown above (or file name suffixes) in order to be able to build both to WebAssembly and other targets.
Then build your WebAssembly binary:
```sh
# To compile with Go
2021-01-28 16:00:27 +01:00
GOOS=js GOARCH=wasm go build -o server.wasm .
# To compile with TinyGo, if your code is compatible
GOOS=js GOARCH=wasm tinygo build -o server.wasm .
2021-01-28 16:00:27 +01:00
```
### Step 2: Create ServiceWorker file
First, check the version of Go/TinyGo you compiled your wasm with:
```sh
$ go version
go version go1.23.4 darwin/arm64
# ^------^
$ tinygo version
tinygo version 0.35.0 darwin/arm64 (using go version go1.23.4 and LLVM version 18.1.2)
# ^----^
```
2021-01-28 16:00:27 +01:00
Create a ServiceWorker file with the following code:
📄 `sw.js`
```js
// Note the 'go.1.23.4' below, that matches the version you just found:
importScripts('https://cdn.jsdelivr.net/gh/golang/go@go1.23.4/misc/wasm/wasm_exec.js')
// If you compiled with TinyGo then, similarly, use:
importScripts('https://cdn.jsdelivr.net/gh/tinygo-org/tinygo@0.35.0/targets/wasm_exec.js')
2025-01-19 11:15:30 +01:00
importScripts('https://cdn.jsdelivr.net/gh/nlepage/go-wasm-http-server@v2.1.0/sw.js')
2021-01-28 16:00:27 +01:00
registerWasmHTTPListener('path/to/server.wasm')
```
2021-01-31 22:24:30 +01:00
By default the server will deploy at the ServiceWorker's scope root, check [`registerWasmHTTPListener()`'s API](https://github.com/nlepage/go-wasm-http-server#registerwasmhttplistenerwasmurl-options) for more information.
2021-01-28 16:00:27 +01:00
You may want to add these additional event listeners in your ServiceWorker:
```js
// Skip installed stage and jump to activating stage
addEventListener('install', (event) => {
event.waitUntil(skipWaiting())
})
// Start controlling clients as soon as the SW is activated
addEventListener('activate', event => {
event.waitUntil(clients.claim())
})
```
### Step 3: Register the ServiceWorker
In your web page(s), register the ServiceWorker:
```html
<script>
// By default the ServiceWorker's scope will be "server/"
navigator.serviceWorker.register('server/sw.js')
</script>
```
Now your web page(s) may start fetching from the server:
```js
// The server will receive a request for "/path/to/resource"
fetch('server/path/to/resource').then(res => {
// use response...
})
```
## API
2021-02-06 18:15:36 +01:00
For Go API see [pkg.go.dev/github.com/nlepage/go-wasm-http-server](https://pkg.go.dev/github.com/nlepage/go-wasm-http-server#section-documentation)
2021-01-31 21:59:22 +01:00
2021-02-06 18:15:36 +01:00
### JavaScript API
2021-01-31 21:59:22 +01:00
2024-10-14 22:24:46 +02:00
### `registerWasmHTTPListener(wasmUrl, options)`
2021-01-31 21:59:22 +01:00
2021-01-31 22:24:30 +01:00
Instantiates and runs the WebAssembly module at `wasmUrl`, and registers a fetch listener forwarding requests to the WebAssembly module's server.
⚠ This function must be called only once in a ServiceWorker, if you want to register several servers you must use several ServiceWorkers.
The server will be "deployed" at the root of the ServiceWorker's scope by default, `base` may be used to deploy the server at a subpath of the scope.
See [ServiceWorkerContainer.register()](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register) for more information about the scope of a ServiceWorker.
2021-01-31 21:59:22 +01:00
#### `wasmUrl`
URL string of the WebAssembly module, example: `"path/to/my-module.wasm"`.
#### `options`
An optional object containing:
- `base` (`string`): Base path of the server, relative to the ServiceWorker's scope.
- `cacheName` (`string`): Name of the [Cache](https://developer.mozilla.org/en-US/docs/Web/API/Cache) to store the WebAssembly binary.
2021-01-31 21:59:22 +01:00
- `args` (`string[]`): Arguments for the WebAssembly module.
- `passthrough` (`(request: Request): boolean`): Optional callback to allow passing the request through to network.
2019-11-26 23:22:12 +01:00
## <abbr title="Frequently Asked Questions">FAQ</abbr> ❓
### Are WebSockets supported?
No, WebSockets arent and wont be supported, because Service Workers cannot intercept websocket connections.
However [Server Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events), which is an alternative to WebSockets, are supported, you can find the code for an example [here](https://github.com/nlepage/go-wasm-http-server/tree/master/docs/hello-sse) and the demo [here](https://nlepage.github.io/go-wasm-http-server/hello-sse/).
### Is it compatible with TinyGo?
Yes, an example and some specific information is available [here](https://github.com/nlepage/go-wasm-http-server/tree/master/docs/tinygo).
2025-01-19 11:29:03 +01:00
## Contributors ✨
Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore-start -->
<!-- markdownlint-disable -->
<table>
<tbody>
<tr>
<td align="center" valign="top" width="14.28%"><a href="https://byjp.me/"><img src="https://avatars.githubusercontent.com/u/42999?v=4?s=100" width="100px;" alt="JP Hastings-Edrei"/><br /><sub><b>JP Hastings-Edrei</b></sub></a><br /><a href="https://github.com/nlepage/go-wasm-http-server/commits?author=jphastings" title="Code">💻</a> <a href="https://github.com/nlepage/go-wasm-http-server/commits?author=jphastings" title="Documentation">📖</a> <a href="#example-jphastings" title="Examples">💡</a></td>
2025-02-06 10:08:56 +01:00
<td align="center" valign="top" width="14.28%"><a href="https://recolude.com/"><img src="https://avatars.githubusercontent.com/u/9094977?v=4?s=100" width="100px;" alt="Eli Davis"/><br /><sub><b>Eli Davis</b></sub></a><br /><a href="https://github.com/nlepage/go-wasm-http-server/commits?author=EliCDavis" title="Code">💻</a></td>
2025-01-19 11:29:03 +01:00
</tr>
</tbody>
</table>
<!-- markdownlint-restore -->
<!-- prettier-ignore-end -->
2019-11-26 23:22:12 +01:00
2025-01-19 11:29:03 +01:00
<!-- ALL-CONTRIBUTORS-LIST:END -->
2019-11-26 23:22:12 +01:00
2025-01-19 11:29:03 +01:00
This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!
2019-11-26 23:22:12 +01:00
## 🤝 Contributing
Contributions, issues and feature requests are welcome!<br />Feel free to check [issues page](https://github.com/nlepage/go-wasm-http-server/issues).
## Show your support
Give a ⭐️ if this project helped you!
## 📝 License
2025-01-19 11:29:03 +01:00
Copyright © 2025 [Nicolas Lepage](https://github.com/nlepage).<br />
2019-11-26 23:22:12 +01:00
This project is [Apache 2.0](https://github.com/nlepage/go-wasm-http-server/blob/master/LICENSE) licensed.
***
2021-02-06 18:15:36 +01:00
_This README was generated with ❤️ by [readme-md-generator](https://github.com/kefranabg/readme-md-generator)_