How to: Author middleware components

Learn how to develop middleware components

Dapr allows custom processing pipelines to be defined by chaining a series of middleware components. In this guide, you’ll learn how to create a middleware component. To learn how to configure an existing middleware component, see Configure middleware components

Writing a custom HTTP middleware

HTTP middlewares in Dapr wrap standard Go net/http handler functions.

Your middleware needs to implement a middleware interface, which defines a GetHandler method that returns a http.Handler callback and an error:

  1. type Middleware interface {
  2. GetHandler(metadata middleware.Metadata) (func(next http.Handler) http.Handler, error)
  3. }

The handler receives a next callback that should be invoked to continue processing the request.

Your handler implementation can include an inbound logic, outbound logic, or both:

  1. func (m *customMiddleware) GetHandler(metadata middleware.Metadata) (func(next http.Handler) http.Handler, error) {
  2. var err error
  3. return func(next http.Handler) http.Handler {
  4. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  5. // Inbound logic
  6. // ...
  7. // Call the next handler
  8. next.ServeHTTP(w, r)
  9. // Outbound logic
  10. // ...
  11. }
  12. }, err
  13. }

Last modified June 19, 2023: Merge pull request #3565 from dapr/aacrawfi/skip-secrets-close (b1763bf)