use the request context with net/http handler (#1696)

This commit is contained in:
Victor Vrantchan
2017-11-30 17:37:49 -05:00
committed by Menghan Li
parent c6b46087ab
commit a4bf341022
3 changed files with 15 additions and 3 deletions

View File

@ -22,6 +22,7 @@ package transport
import ( import (
"net" "net"
"net/http"
"google.golang.org/grpc/codes" "google.golang.org/grpc/codes"
@ -43,3 +44,8 @@ func ContextErr(err error) StreamError {
} }
return streamErrorf(codes.Internal, "Unexpected error from context packet: %v", err) return streamErrorf(codes.Internal, "Unexpected error from context packet: %v", err)
} }
// contextFromRequest returns a background context.
func contextFromRequest(r *http.Request) context.Context {
return context.Background()
}

View File

@ -23,6 +23,7 @@ package transport
import ( import (
"context" "context"
"net" "net"
"net/http"
"google.golang.org/grpc/codes" "google.golang.org/grpc/codes"
@ -44,3 +45,8 @@ func ContextErr(err error) StreamError {
} }
return streamErrorf(codes.Internal, "Unexpected error from context packet: %v", err) return streamErrorf(codes.Internal, "Unexpected error from context packet: %v", err)
} }
// contextFromRequest returns a context from the HTTP Request.
func contextFromRequest(r *http.Request) context.Context {
return r.Context()
}

View File

@ -284,12 +284,12 @@ func (ht *serverHandlerTransport) WriteHeader(s *Stream, md metadata.MD) error {
func (ht *serverHandlerTransport) HandleStreams(startStream func(*Stream), traceCtx func(context.Context, string) context.Context) { func (ht *serverHandlerTransport) HandleStreams(startStream func(*Stream), traceCtx func(context.Context, string) context.Context) {
// With this transport type there will be exactly 1 stream: this HTTP request. // With this transport type there will be exactly 1 stream: this HTTP request.
var ctx context.Context ctx := contextFromRequest(ht.req)
var cancel context.CancelFunc var cancel context.CancelFunc
if ht.timeoutSet { if ht.timeoutSet {
ctx, cancel = context.WithTimeout(context.Background(), ht.timeout) ctx, cancel = context.WithTimeout(ctx, ht.timeout)
} else { } else {
ctx, cancel = context.WithCancel(context.Background()) ctx, cancel = context.WithCancel(ctx)
} }
// requestOver is closed when either the request's context is done // requestOver is closed when either the request's context is done