trpc.group/trpc-go/trpc-go@v1.0.3/http/value_detached_transport.go (about)

     1  //
     2  //
     3  // Tencent is pleased to support the open source community by making tRPC available.
     4  //
     5  // Copyright (C) 2023 THL A29 Limited, a Tencent company.
     6  // All rights reserved.
     7  //
     8  // If you have downloaded a copy of the tRPC source code from Tencent,
     9  // please note that tRPC source code is licensed under the  Apache 2.0 License,
    10  // A copy of the Apache 2.0 License is included in this file.
    11  //
    12  //
    13  
    14  package http
    15  
    16  import (
    17  	"net/http"
    18  	"net/http/httptrace"
    19  )
    20  
    21  // newValueDetachedTransport creates a new valueDetachedTransport.
    22  func newValueDetachedTransport(r http.RoundTripper) http.RoundTripper {
    23  	return &valueDetachedTransport{RoundTripper: r}
    24  }
    25  
    26  // valueDetachedTransport detaches ctx value before RoundTripping a http.Request.
    27  type valueDetachedTransport struct {
    28  	http.RoundTripper
    29  }
    30  
    31  // RoundTrip implements http.RoundTripper.
    32  func (vdt *valueDetachedTransport) RoundTrip(req *http.Request) (*http.Response, error) {
    33  	ctx := req.Context()
    34  	trace := httptrace.ContextClientTrace(ctx)
    35  	ctx = detachCtxValue(ctx)
    36  	if trace != nil {
    37  		ctx = httptrace.WithClientTrace(ctx, trace)
    38  	}
    39  	req = req.WithContext(ctx)
    40  	return vdt.RoundTripper.RoundTrip(req)
    41  }
    42  
    43  // CancelRequest implements canceler.
    44  func (vdt *valueDetachedTransport) CancelRequest(req *http.Request) {
    45  	// canceler judges whether RoundTripper implements
    46  	// the http.RoundTripper.CancelRequest function.
    47  	// CancelRequest is supported after go 1.5 or 1.6.
    48  	type canceler interface{ CancelRequest(*http.Request) }
    49  	if v, ok := vdt.RoundTripper.(canceler); ok {
    50  		v.CancelRequest(req)
    51  	}
    52  }