The documentation you are viewing is for Dapr v1.4 which is an older version of Dapr. For up-to-date documentation, see the latest version.

中间件

通过添加中间件组件自定义处理管道

Dapr 允许通过链接一系列中间件组件来定义自定义处理管道。 请求在路由到用户代码之前经过所有已定义的中间件组件,然后在返回到客户机之前,按相反顺序经过已定义的中间件,如下图中所示。

Configuring middleware pipelines

启动后, Dapr sidecar 会构建中间件处理管道。 默认情况下,管道由 追踪中间件 和 CORS 中间件组成。 其他中间件,由 Dapr configuration 配置,按照定义的顺序添加到管道中。 管道适用于所有 Dapr API 终结点,包括状态,发布/订阅,服务调用,绑定,安全性和其他。

The following configuration example defines a custom pipeline that uses a OAuth 2.0 middleware and an uppercase middleware component. 在这种情况下,在转发到用户代码之前,所有请求都将通过 OAuth 2.0 协议进行授权,并转换为大写文本。

apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
  name: pipeline
  namespace: default
spec:
  httpPipeline:
    handlers:
    - name: oauth2
      type: middleware.http.oauth2
    - name: uppercase
      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

编写自定义中间件

Dapr 使用 FastHTTP 来实现其的 HTTP 服务器。 因此,您的 HTTP 中间件也需要编写为 FastHTTP handler。 Your middleware needs to implement a middleware interface, which defines a GetHandler method that returns fasthttp.RequestHandler and error:

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

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


func (m *customMiddleware) GetHandler(metadata Metadata) (func(fasthttp.RequestHandler) fasthttp.RequestHandler, error) {
  var err error
  return func(h fasthttp.RequestHandler) fasthttp.RequestHandler {
    return func(ctx *fasthttp.RequestCtx) {
      // inboud logic
      h(ctx)  // call the downstream handler
      // outbound logic
    }
  }, err
}

添加新的中间件组件

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

在接受了 components-contrib 变更后,针对 Dapr 运行时仓库 提交另一个 pull 请求,以注册新的中间件类型。 您需要修改runtime.WithHTTPMiddleware方法中的**cmd/daprd/main.go方法,将您的中间件注册到Dapr的运行时。

相关链接