Skip to content

Instantly share code, notes, and snippets.

@ldemailly
Created July 18, 2024 23:58
Show Gist options
  • Save ldemailly/ddaa31a172350c0014b92c9be2037375 to your computer and use it in GitHub Desktop.
Save ldemailly/ddaa31a172350c0014b92c9be2037375 to your computer and use it in GitHub Desktop.
minimal version that doesn't serve http request with `GOOS=wasip1 GOARCH=wasm go run -exec wasirun main.go`
package main
import (
"log"
"net/http"
"os"
"os/signal"
"github.com/stealthrocket/net/wasip1"
)
func main() {
go func() {
listener, err := wasip1.Listen("tcp", "127.0.0.1:3000")
if err != nil {
panic(err)
}
server := &http.Server{
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("Hello, World!"))
}),
}
log.Printf("Serving in goroutine.")
if err := server.Serve(listener); err != nil {
panic(err)
}
}()
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
log.Printf("Waiting in main goroutine.")
<-c
log.Printf("Interrupt received.")
}
@ldemailly
Copy link
Author

yet this works

package main

import (
	"log"
	"net/http"

	"github.com/stealthrocket/net/wasip1"
)

func main() {
	c := make(chan struct{}, 1)
	go func() {
		listener, err := wasip1.Listen("tcp", ":3000")
		if err != nil {
			panic(err)
		}

		server := &http.Server{
			Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
				w.WriteHeader(http.StatusOK)
				w.Write([]byte("Hello, World!"))
			}),
		}
		log.Printf("Serving in goroutine on :3000")
		if err := server.Serve(listener); err != nil {
			log.Println(err)
		}
		c <- struct{}{}
	}()
	log.Printf("Waiting in main goroutine.")
	<-c
	log.Printf("End received.")
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment