[golang] replace/modify context in StreamServerInterceptor

1,633 views
Skip to first unread message

flazz...@gmail.com

unread,
Nov 10, 2016, 5:28:05 PM11/10/16
to grpc.io
Hi,

I'm implementing a StreamServerInterceptor.

func StreamServerInterceptor(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
    // do some stuff, like attach a tracer to the context
    return handler(srv, ss)
}

I can read the inbound ctx from ss.Context() but I can't figure out a way to replace it on the stream with a derivative Context. The best I can thing of is to wrap ss with some other grpc.ServerStream that does what I want. Is this the canonical way to do this?

Thanks,

-Franco

Qi Zhao

unread,
Nov 10, 2016, 6:25:57 PM11/10/16
to flazz...@gmail.com, grpc.io
Yes you can do that. And we recently add https://github.com/grpc/grpc-go/blob/master/tap/tap.go and you can also use that attach your stuff onto the context in the very early stage (so that ss.Context() gets the ctx you expect). But keep in mind they are still EXPERIMENTAL and might be subject to change later. 

Thanks,

-Franco

--
You received this message because you are subscribed to the Google Groups "grpc.io" group.
To unsubscribe from this group and stop receiving emails from it, send an email to grpc-io+unsubscribe@googlegroups.com.
To post to this group, send email to grp...@googlegroups.com.
Visit this group at https://groups.google.com/group/grpc-io.
To view this discussion on the web visit https://groups.google.com/d/msgid/grpc-io/7146f65d-254d-4dbc-9d04-44e385e6e9d3%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
Thanks,
-Qi

Francesco Lazzarino

unread,
Nov 10, 2016, 7:36:44 PM11/10/16
to grpc.io
Thanks Qi, I'll look into that.

If it helps anyone the wrapper looks like this:

type serverStreamWrapper struct {
ss  grpc.ServerStream
ctx context.Context
}

func (w serverStreamWrapper) Context() context.Context        { return w.ctx }
func (w serverStreamWrapper) RecvMsg(msg interface{}) error   { return w.ss.RecvMsg(msg) }
func (w serverStreamWrapper) SendMsg(msg interface{}) error   { return w.ss.SendMsg(msg) }
func (w serverStreamWrapper) SendHeader(md metadata.MD) error { return w.ss.SendHeader(md) }
func (w serverStreamWrapper) SetHeader(md metadata.MD) error  { return w.ss.SetHeader(md) }
func (w serverStreamWrapper) SetTrailer(md metadata.MD)       { w.ss.SetTrailer(md) }

akkif...@gmail.com

unread,
Apr 16, 2017, 9:34:12 PM4/16/17
to grpc.io
Even simpler:

type serverStreamWrapper struct {
grpc.ServerStream

ctx context.Context
}

func (w *serverStreamWrapper) Context() context.Context { return w.ctx }
Reply all
Reply to author
Forward
0 new messages