Go - Kit 笔记 - 02 - Transport-http

本文主要探讨Go-Kit中的Transport传输层,包括Server和Client结构的详细解析。Server结构封装端点并可添加到HTTP服务,而Client则用于发送HTTP请求,类似于一个http爬虫。在Server执行流程中,涉及before、解码、端点执行、after、编码和finalizer等步骤;Client的执行顺序则包括解码、before、发送请求、after和编码。建议结合具体示例学习以深化理解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Transport – 传输层

位于github.com/go-kit/kit/transport/,go-kit目前支持grpc、http、httprp、nats、netrpc、thrift,传输层的作用是封装端点。使端点可以被不同的传输协议调用。

Server结构

Server结构的作用是把端点封装成http.Handlerhttp.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是可以自定义的。
                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值