Overview

General overview on set up of middleware components for Dapr

Dapr allows custom processing pipelines to be defined by chaining a series of middleware components. Middleware pipelines are defined in Dapr configuration files. As with other building block components, middleware components are extensible and can be found in the components-contrib repo.

Middleware in Dapr is described using a Component file with the following schema:

  1. apiVersion: dapr.io/v1alpha1
  2. kind: Component
  3. metadata:
  4. name: <COMPONENT NAME>
  5. namespace: <NAMESPACE>
  6. spec:
  7. type: middleware.http.<MIDDLEWARE TYPE>
  8. version: v1
  9. metadata:
  10. - name: <KEY>
  11. value: <VALUE>
  12. - name: <KEY>
  13. value: <VALUE>
  14. ...

The type of middleware is determined by the type field. Component setting values such as rate limits, OAuth credentials and other settings are put in the metadata section. Even though metadata values can contain secrets in plain text, it is recommended that you use a secret store.

Next, a Dapr configuration defines the pipeline of middleware components for your application.

  1. apiVersion: dapr.io/v1alpha1
  2. kind: Configuration
  3. metadata:
  4. name: appconfig
  5. spec:
  6. httpPipeline:
  7. handlers:
  8. - name: <COMPONENT NAME>
  9. type: middleware.http.<MIDDLEWARE TYPE>
  10. - name: <COMPONENT NAME>
  11. type: middleware.http.<MIDDLEWARE TYPE>

Writing a custom middleware

Dapr uses FastHTTP to implement its HTTP server. Hence, your HTTP middleware needs to be written as a FastHTTP handler. Your middleware needs to implement a middleware interface, which defines a GetHandler method that returns a fasthttp.RequestHandler:

  1. type Middleware interface {
  2. GetHandler(metadata Metadata) (func(h fasthttp.RequestHandler) fasthttp.RequestHandler, error)
  3. }

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

  1. func GetHandler(metadata Metadata) fasthttp.RequestHandler {
  2. return func(h fasthttp.RequestHandler) fasthttp.RequestHandler {
  3. return func(ctx *fasthttp.RequestCtx) {
  4. // inboud logic
  5. h(ctx) // call the downstream handler
  6. // outbound logic
  7. }
  8. }
  9. }

Adding new middleware components

Your middleware component can be contributed to the components-contrib repository.

After the components-contrib change has been accepted, submit another pull request against the Dapr runtime repository to register the new middleware type. You’ll need to modify runtime.WithHTTPMiddleware method in cmd/daprd/main.go to register your middleware with Dapr’s runtime.

Related links

Last modified March 18, 2021: Merge pull request #1321 from dapr/aacrawfi/logos (9a399d5)