Skip to content

Embed your Go HTTP handlers in a ServiceWorker and emulate an HTTP server!

License

Notifications You must be signed in to change notification settings

nlepage/go-wasm-http-server

Repository files navigation

Welcome to go-wasm-http-server πŸ‘‹

Go Reference License: Apache 2.0

Embed your Go HTTP handlers in a ServiceWorker (using WebAssembly) and emulate an HTTP server!

Examples

How?

Below is a talk given at the Go devroom of FOSDEM 2021 explaining how go-wasm-http-server works.

Warning

go-wasm-http-server has suffered major changes since this talk, be aware that it is not accurate anymore on several aspects. Please refer to the documentation below for up to date usage of go-wasm-http-server.

Deploy a Go HTTP server in your browser Youtube link

The slides are available here.

Why?

go-wasm-http-server can help you put up a demonstration for a project without actually running a Go HTTP server.

Requirements

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. See the TinyGo specific details below.

Usage

Step 1: Build to js/wasm

In your Go code, replace http.ListenAndServe() (or net.Listen() + http.Serve()) by wasmhttp.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/v2"
)

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:

# To compile with Go
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  .

Step 2: Create ServiceWorker file

First, check the version of Go/TinyGo you compiled your wasm with:

$ 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)
#              ^----^

Create a ServiceWorker file with the following code:

πŸ“„ sw.js

// Note the 'go.1.23.4' below, that matches the version you just found:
importScripts('https://cdn.jsdelivr.net/gh/golang/[email protected]/misc/wasm/wasm_exec.js')
// If you compiled with TinyGo then, similarly, use:
importScripts('https://cdn.jsdelivr.net/gh/tinygo-org/[email protected]/targets/wasm_exec.js')

importScripts('https://cdn.jsdelivr.net/gh/nlepage/[email protected]/sw.js')

registerWasmHTTPListener('path/to/server.wasm')

By default the server will deploy at the ServiceWorker's scope root, check registerWasmHTTPListener()'s API for more information.

You may want to add these additional event listeners in your ServiceWorker:

// 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:

<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:

// The server will receive a request for "/path/to/resource"
fetch('server/path/to/resource').then(res => {
  // use response...
})

API

For Go API see pkg.go.dev/github.com/nlepage/go-wasm-http-server

JavaScript API

registerWasmHTTPListener(wasmUrl, options)

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() for more information about the scope of a ServiceWorker.

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 to store the WebAssembly binary.
  • args (string[]): Arguments for the WebAssembly module.
  • passthrough ((request: Request): boolean): Optional callback to allow passing the request through to network.

FAQ ❓

Are WebSockets supported?

No, WebSockets aren’t and won’t be supported, because Service Workers cannot intercept websocket connections.

However Server Sent Events, which is an alternative to WebSockets, are supported, you can find the code for an example here and the demo here.

Is it compatible with TinyGo?

Yes, an example and some specific information is available here.

Contributors ✨

Thanks goes to these wonderful people (emoji key):

JP Hastings-Edrei
JP Hastings-Edrei

πŸ’» πŸ“– πŸ’‘
Eli Davis
Eli Davis

πŸ’» πŸ›

This project follows the all-contributors specification. Contributions of any kind welcome!

🀝 Contributing

Contributions, issues and feature requests are welcome!
Feel free to check issues page.

Show your support

Give a ⭐️ if this project helped you!

πŸ“ License

Copyright Β© 2025 Nicolas Lepage.
This project is Apache 2.0 licensed.


This README was generated with ❀️ by readme-md-generator

About

Embed your Go HTTP handlers in a ServiceWorker and emulate an HTTP server!

Topics

Resources

License

Code of conduct

Stars

Watchers

Forks

Contributors 3

  •  
  •  
  •