- [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))
- [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))
[](https://youtu.be/O2RB_8ircdE)
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 (
wasmhttp "github.com/nlepage/go-wasm-http-server"
)
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
GOOS=js GOARCH=wasm go build -o server.wasm .
```
### Step 2: Create ServiceWorker file
Create a ServiceWorker file with the following code:
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.
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.