I'd like to try an http server via WebAssembly on Go. I think that compiling go for webassembly outside the browser is not supported in go 1.20, and that the net/http libraries aren't included in tinygo.
I tried to do it with gotip
after reading https://stackoverflow.com/a/76091829 (thanks @TachyonicBytes), but whenever I tried to start the server (or any blocking/waiting function), I got an error: fatal error: all goroutines are asleep - deadlock!
. I tried moving things to a goroutine with wait functions and that either simply ended the function, or gave the same error.
Here's how I ran it:
go install golang.org/dl/gotip@latest
gotip download
GOOS=wasip1 GOARCH=wasm gotip build -o server.wasm server.go && wasm3 server.wasm
Here's the example server.go
:
package main
import (
"fmt"
"net/http"
"sync"
)
func main() {
s := http.Server{
Addr: ":8080",
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, World!"))
}),
}
fmt.Println("about to serve")
var wg sync.WaitGroup
wg.Add(1)
go func() {
err := s.ListenAndServe()
if err != nil {
fmt.Printf("Unable to serve: %v\n", err)
}
wg.Done()
fmt.Println("serving stopped")
}()
wg.Wait()
fmt.Println("started up server")
}
So, is this just because go 1.21 is a WIP, because I'm failing to understand the proper way to start a blocking function, or because this sort of thing won't be supported in go 1.21?
I tried to start a go server in a server side webassembly runner wasm3 on an Intel Mac. I expected it to serve http, but found it either threw an error, or exited immediately.