Transport – 传输层
位于github.com/go-kit/kit/transport/
,go-kit目前支持grpc、http、httprp、nats、netrpc、thrift
,传输层的作用是封装端点。使端点可以被不同的传输协议调用。
Server结构
Server结构的作用是把端点封装成http.Handler
,http.Handler
位于net/http/server.go
中,实则是一个接口,定义如下:
type Handler interface {
ServeHTTP(ResponseWriter, *Request)
}
注:如果对```net/http```包不太了解,可以看一看《go-web编程》。
Server结构定义如下:
type ErrorEncoder func(ctx context.Context, err error, w http.ResponseWriter)
type DecodeRequestFunc func(context.Context, *http.Request) (request interface{
}, err error)
type EncodeRequestFunc func(context.Context, *http.Request, interface{
}) error
type Server struct {
e endpoint.Endpoint //端点
dec DecodeRequestFunc //解码函数,需要自定义
enc EncodeResponseFunc //编码函数,需要自定义
before []RequestFunc //前置函数
after []ServerResponseFunc //后置函数
errorEncoder ErrorEncoder //错误函数
finalizer []ServerFinalizerFunc //终结器函数
logger log.Logger //日志
}
从NewServer
开始跟代码:
type ServerOption func(*Server)
func NewServer(
e endpoint.Endpoint, //e,不解释
dec DecodeRequestFunc, //调用端点之前,会调用dec对数据进行解码
enc EncodeResponseFunc, //调用端点之后,会调用enc对数据进行编码
options ...ServerOption, //看函数体中的for循环。
) *Server {
s := &Server{
e: e,
dec: dec,
enc: enc,
errorEncoder: DefaultErrorEncoder, //transport/http/server.go里面有定义,有兴趣的可以看一眼。
logger: log.NewNopLogger(), //go-kit自己的log模块,有机会看。
}
for _, option := range options {
//循环执行option。option是可以自定义的。