go-micro wrappers的问题

如文档里提到的:
这里的server.Request参数除了能获取服务名、方法名外,并不能获取HeaderBody的数据,作为一个中间件使用,怎样才能拦截到http数据?

func logWrapper(fn server.HandlerFunc) server.HandlerFunc {
    return func(ctx context.Context, req server.Request, rsp interface{}) error {
        fmt.Printf("[%v] server request: %s", time.Now(), req.Endpoint())
        
        fmt.Println(req.Header())//打印结果:map[]
        
        return fn(ctx, req, rsp)
    }
}

server.Request源码是这样的

// Request is a synchronous request interface  
type Request interface {  
   // Service name requested  
  Service() string  
  // The action requested  
  Method() string  
  // Endpoint name requested  
  Endpoint() string  
  // Content type provided  
  ContentType() string  
  // Header of the request  
  Header() map\[string\]string  
  // Body is the initial decoded value  
  Body() interface{}  
   // Read the undecoded request body  
  Read() (\[\]byte, error)  
   // The encoded message stream  
  Codec() codec.Reader  
  // Indicates whether its a stream  
  Stream() bool  
}
阅读 2.9k
1 个回答
func logWrapper(fn server.HandlerFunc) server.HandlerFunc {
    return func(ctx context.Context, req server.Request, rsp interface{}) error {
        //开始不知道req.Body()是个什么东西,虽然能print出东西来,直到typeof后才发现原来它是*go_api.Request
        //fmt.Println(reflect.TypeOf(req.Body()))//*go_api.Request
  
        //既然知道它的类型,那就好办了
        request:=req.Body().(*go_api.Request)
        
        fmt.Println(request.Header)
        fmt.Println(request.Body)
        
        return fn(ctx, req, rsp)
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题