Skip to content

ServerInterceptor how to get header/trailer data #4317

@zhenjunMa

Description

@zhenjunMa

scene

I use grpc.UnaryServerInterceptor/grpc.StreamServerInterceptor to do some common logic before/after the biz code.

in the common logic, i want to get request header before biz code and get response header/trailer after biz code, but i found i can't do the latter.

my implementation

var unaryInterceptor grpc.UnaryServerInterceptor
unaryInterceptor = func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error){
                 //here i can get the header when request come
		md, ok := metadata.FromIncomingContext(ctx)
		if ok {
			//do something...
		}

                 //do biz logic
		resp, err = handler(ctx, req)

                 //here,i want get header/trailer to do something
                 //finally i use reflect achieve the goal
		stream := grpc.ServerTransportStreamFromContext(ctx)
		v := reflect.ValueOf(stream)
		fmt.Printf("header: %v", reflect.Indirect(v).FieldByName("header"))
		fmt.Printf("trailer: %v", reflect.Indirect(v).FieldByName("trailer"))

		return
	}

question

I can't find an easy way to get header/trailer after the biz logic, so i use reflect.
In my opinion, get header/trailer after the biz logic maybe a feature that many people need, so did i lost some doc about this or this feature is indeed unavailable now, need a PR? :)

looking forward reply.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions