概述

General overview on set up of middleware components for Dapr

Dapr 允许通过链接一系列中间件组件来定义自定义处理管道。 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. 因此,您的 HTTP 中间件也需要编写为 FastHTTP handler。 您的中间件需要实现 Middleware 接口,该接口定义 GetHandler 方法,该方法返回 fasthttp.RequestHandler:

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

您的 handler 实现可以包含任何入站(inbound)逻辑和出站(outbound)逻辑或两者兼有:

  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

您的中间件组件可以贡献到 components-contrib 仓库

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 January 1, 0001