go4.org@v0.0.0-20230225012048-214862532bf5/ctxutil/ctxutil.go (about)

     1  /*
     2  Copyright 2015 The Go4 Authors
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8       http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  // Package ctxutil contains golang.org/x/net/context related utilities.
    18  package ctxutil // import "go4.org/ctxutil"
    19  
    20  import (
    21  	"net/http"
    22  
    23  	"golang.org/x/net/context"
    24  	"golang.org/x/oauth2"
    25  )
    26  
    27  // HTTPClient is the context key to use with golang.org/x/net/context's WithValue function
    28  // to associate an *http.Client value with a context.
    29  //
    30  // We use the same value as the oauth2 package (which first introduced this key) rather
    31  // than creating a new one and forcing users to possibly set two.
    32  var HTTPClient = oauth2.HTTPClient
    33  
    34  // Client returns the HTTP client to use for the provided context.
    35  // If ctx is non-nil and has an associated HTTP client, that client is returned.
    36  // Otherwise, http.DefaultClient is returned.
    37  func Client(ctx context.Context) *http.Client {
    38  	if ctx != nil {
    39  		if hc, ok := ctx.Value(HTTPClient).(*http.Client); ok {
    40  			return hc
    41  		}
    42  	}
    43  	return http.DefaultClient
    44  }