本文主要研究一下dapr的Pipeline

Pipeline

dapr/pkg/middleware/http/http_pipeline.go

import (
    "github.com/dapr/dapr/pkg/config"
    "github.com/valyala/fasthttp"
)

type Middleware func(h fasthttp.RequestHandler) fasthttp.RequestHandler

// HTTPPipeline defines the middleware pipeline to be plugged into Dapr sidecar
type Pipeline struct {
    Handlers []Middleware
}

func BuildHTTPPipeline(spec config.PipelineSpec) (Pipeline, error) {
    return Pipeline{}, nil
}

func (p Pipeline) Apply(handler fasthttp.RequestHandler) fasthttp.RequestHandler {
    for i := len(p.Handlers) - 1; i >= 0; i-- {
        handler = p.Handlers[i](handler)
    }
    return handler
}
Pipeline定义了Handlers属性,是一个Middleware数组;Pipeline定义了Apply方法,它会从后往前挨个执行Middleware函数;Middleware函数接收fasthttp.RequestHandler,返回fasthttp.RequestHandler

实例

dapr/pkg/http/server.go

type server struct {
    config      ServerConfig
    tracingSpec config.TracingSpec
    metricSpec  config.MetricSpec
    pipeline    http_middleware.Pipeline
    api         API
}

func (s *server) useComponents(next fasthttp.RequestHandler) fasthttp.RequestHandler {
    return s.pipeline.Apply(next)
}
server定义了pipeline属性,其useComponents方法接收fasthttp.RequestHandler),对其执行pipeline.Apply

小结

dapr的Pipeline定义了Handlers属性,是一个Middleware数组;Pipeline定义了Apply方法,它会从后往前挨个执行Middleware函数;Middleware函数接收fasthttp.RequestHandler,返回fasthttp.RequestHandler。

doc


codecraft
11.9k 声望2k 粉丝

当一个代码的工匠回首往事时,不因虚度年华而悔恨,也不因碌碌无为而羞愧,这样,当他老的时候,可以很自豪告诉世人,我曾经将代码注入生命去打造互联网的浪潮之巅,那是个很疯狂的时代,我在一波波的浪潮上留下...