Middleware

Customize processing pipelines by adding middleware components

Dapr allows custom processing pipelines to be defined by chaining a series of middleware components. A request goes through all defined middleware components before it’s routed to user code, and then goes through the defined middleware, in reverse order, before it’s returned to the client, as shown in the following diagram.

Middleware - 图1

Configuring middleware pipelines

When launched, a Dapr sidecar constructs a middleware processing pipeline. By default the pipeline consists of tracing middleware and CORS middleware. Additional middleware, configured by a Dapr configuration, can be added to the pipeline in the order they are defined. The pipeline applies to all Dapr API endpoints, including state, pub/sub, service invocation, bindings, security and others.

The following configuration example defines a custom pipeline that uses a OAuth 2.0 middleware and an uppercase middleware component. In this case, all requests are authorized through the OAuth 2.0 protocol, and transformed to uppercase text, before they are forwarded to user code.

  1. apiVersion: dapr.io/v1alpha1
  2. kind: Configuration
  3. metadata:
  4. name: pipeline
  5. namespace: default
  6. spec:
  7. httpPipeline:
  8. handlers:
  9. - name: oauth2
  10. type: middleware.http.oauth2
  11. - name: uppercase
  12. type: middleware.http.uppercase

As with other building block components, middleware components are extensible and can be found in the supported Middleware reference and in the components-contrib repo.

See all middleware components

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 fasthttp.RequestHandler and error:

  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 (m *customMiddleware) GetHandler(metadata Metadata) (func(fasthttp.RequestHandler) fasthttp.RequestHandler, error) {
  2. var err error
  3. return func(h fasthttp.RequestHandler) fasthttp.RequestHandler {
  4. return func(ctx *fasthttp.RequestCtx) {
  5. // inboud logic
  6. h(ctx) // call the downstream handler
  7. // outbound logic
  8. }
  9. }, err
  10. }

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.

Last modified February 18, 2022: Update setup-jetstream.md (#2200) (428d8c2)