github.com/xmidt-org/webpa-common@v1.11.9/xhttp/context.go (about)

     1  package xhttp
     2  
     3  import (
     4  	"context"
     5  	"net/http"
     6  
     7  	gokithttp "github.com/go-kit/kit/transport/http"
     8  )
     9  
    10  type errorEncoderKey struct{}
    11  
    12  // GetErrorEncoder returns the go-kit HTTP ErrorEncoder associated with the context.  If no
    13  // encoder is present within the context, DefaultErrorEncoder is returned.
    14  func GetErrorEncoder(ctx context.Context) gokithttp.ErrorEncoder {
    15  	if ee, ok := ctx.Value(errorEncoderKey{}).(gokithttp.ErrorEncoder); ok {
    16  		return ee
    17  	}
    18  
    19  	return gokithttp.DefaultErrorEncoder
    20  }
    21  
    22  // WithErrorEncoder associates a go-kit ErrorEncoder with the context.  If the supplied ErrorEncoder
    23  // is nil, the supplied context is returned as is.
    24  func WithErrorEncoder(ctx context.Context, ee gokithttp.ErrorEncoder) context.Context {
    25  	if ee == nil {
    26  		return ctx
    27  	}
    28  
    29  	return context.WithValue(ctx, errorEncoderKey{}, ee)
    30  }
    31  
    32  type httpClientKey struct{}
    33  
    34  // GetClient returns the HTTP client associated with the context.  If no client is present
    35  // in the context, http.DefaultClient is returned.
    36  func GetClient(ctx context.Context) Client {
    37  	if c, ok := ctx.Value(httpClientKey{}).(Client); ok {
    38  		return c
    39  	}
    40  
    41  	return http.DefaultClient
    42  }
    43  
    44  // WithClient associates an HTTP Client with the context.  If the supplied client is
    45  // nil, the supplied context is returned as is.
    46  func WithClient(ctx context.Context, c Client) context.Context {
    47  	if c == nil {
    48  		return ctx
    49  	}
    50  
    51  	return context.WithValue(ctx, httpClientKey{}, c)
    52  }