http-wasm/http-wasm-host-go

Use basic Middleware

Closed this issue · 1 comments

Using basic Middleware and implementing the host yourself, I have two questions:

  1. What is the usage scenario of Features?
  2. Is it normal for a wasm file to be global and a Middleware? Call the HandleRequest function every time you request?
type host struct {
	apihandler.UnimplementedHost
}

// GetURI implements the same method as documented on handler.Host.
func (h host) GetURI(ctx context.Context) string {
	rs := ctx.Value(requestStateKey{}).(*requestState)
	return rs.r.URL.Path
}

// SetURI implements the same method as documented on handler.Host.
func (h host) SetURI(ctx context.Context, uri string) {
	rs := ctx.Value(requestStateKey{}).(*requestState)
	rs.r.RequestURI = uri
}

var mw handler.Middleware

func init() {
	ctx := context.Background()
	wasmfile, err := os.ReadFile("./router/main.wasm")
	if err != nil {
		log.Panicln(err)
	}
	mw, err = handler.NewMiddleware(ctx, wasmfile, host{}, handler.Logger(api.ConsoleLogger{}))
	if err != nil {
		log.Panicln(err)
	}
}

var wasmHello = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	ctx := context.Background()
	rs := &requestState{w: w, r: r}
	rs.enableFeatures(mw.Features())
	ctx = context.WithValue(ctx, requestStateKey{}, rs)
	outCtx, ctxNext, err := mw.HandleRequest(ctx)
	fmt.Println(outCtx, ctxNext, err)
})

func main() {
	http.Handle("/", wasmHello)
	http.ListenAndServe(":8000", nil)
}

What is the usage scenario of Features?

Features is discussed in abstract here https://http-wasm.io/http-handler-abi/#features and also in godoc here https://pkg.go.dev/github.com/http-wasm/http-wasm-guest-tinygo@v0.2.0/handler/api#Features

The most common use of features is to opt-into expensive features such as response buffering. Because an HTTP body can be very large, there can be a high cost to always copying it to memory. So, you use a feature flag to enable it.

Is it normal for a wasm file to be global and a Middleware? Call the HandleRequest function every time you request?

Yes, this is by design. The guest is initialized and re-used per request to avoid the latency of re-initializing per request. It is recommended to use an existing host which does this vs create your own, as these projects implement that process and doing on own is very complicated.

For example Express (JS) or net/http (Go).

Last thing, can you please use slack room for questions, next time? Issues list is for changes to this codebase. It is easier to answer general questions on chat. https://join.slack.com/t/newworkspace-6gk8596/shared_invite/zt-1rivu8e1g-qxn595SvkrbZBxvrA~aX1w