Turn a middlware into a caddyhttp.Middleware

Are there existing patterns or is it even possible at all to turn a middleware (func(http.Handler) http.Handler into a a caddyhttp.Middleware?
I’m thinking about developing a middleware and would like to provide the functionality as Caddy plugin aswell.

Currently I’m thinking about something like this which turns the caddyhttp.Handler into a http.Handler.

func (m Middleware) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
	var err error
	adapter := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		err = next.ServeHTTP(w, r)
	})
	m.myMiddleware(adapter).ServeHTTP(w, r)
	return err
}

But this way the errors from my middleware are probably not properly returned.
What does happen if a caddyhttp.Middleware or caddyhtpp.Handler does not return an error but set the error on the http.ResponseWriter itself?

Another thing it thought about is wrapping the ResponseWriter to construct the error my self.

Thank you for working on Caddy and thank you already for inputs on this!

By this do you mean that it writes an HTTP error response? In that case, it’ll just get written as a response directly to the client.

Returning an err in the middleware pipeline triggers Caddy’s error routes (e.g. handle_errors). If you don’t care to handle errors this way in Caddy (to write a custom response given the error that bubbled up), then you don’t need to worry about it.

This topic was automatically closed after 30 days. New replies are no longer allowed.