github.com/cs3org/reva/v2@v2.27.7/pkg/rhttp/client.go (about)

     1  // Copyright 2018-2021 CERN
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  //
    15  // In applying this license, CERN does not waive the privileges and immunities
    16  // granted to it by virtue of its status as an Intergovernmental Organization
    17  // or submit itself to any jurisdiction.
    18  
    19  package rhttp
    20  
    21  import (
    22  	"context"
    23  	"crypto/tls"
    24  	"io"
    25  	"net/http"
    26  
    27  	"go.opencensus.io/plugin/ochttp"
    28  
    29  	ctxpkg "github.com/cs3org/reva/v2/pkg/ctx"
    30  	"github.com/pkg/errors"
    31  )
    32  
    33  // GetHTTPClient returns an http client with open census tracing support.
    34  // TODO(labkode): harden it.
    35  // https://medium.com/@nate510/don-t-use-go-s-default-http-client-4804cb19f779
    36  func GetHTTPClient(opts ...Option) *http.Client {
    37  	options := newOptions(opts...)
    38  
    39  	tr := http.DefaultTransport.(*http.Transport).Clone()
    40  	tr.DisableKeepAlives = options.DisableKeepAlive
    41  	tr.TLSClientConfig = &tls.Config{
    42  		InsecureSkipVerify: options.Insecure,
    43  	}
    44  
    45  	httpClient := &http.Client{
    46  		Timeout: options.Timeout,
    47  		Transport: &ochttp.Transport{
    48  			Base: tr,
    49  		},
    50  	}
    51  
    52  	return httpClient
    53  }
    54  
    55  // NewRequest creates an HTTP request that sets the token if it is passed in ctx.
    56  func NewRequest(ctx context.Context, method, url string, body io.Reader) (*http.Request, error) {
    57  	httpReq, err := http.NewRequest(method, url, body)
    58  	if err != nil {
    59  		return nil, errors.Wrap(err, "utils: error creating request")
    60  	}
    61  
    62  	// TODO(labkode): make header / auth configurable
    63  	tkn, ok := ctxpkg.ContextGetToken(ctx)
    64  	if ok {
    65  		httpReq.Header.Set(ctxpkg.TokenHeader, tkn)
    66  	}
    67  
    68  	httpReq = httpReq.WithContext(ctx)
    69  	return httpReq, nil
    70  }