go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/r2/opt_tls.go (about)

     1  /*
     2  
     3  Copyright (c) 2023 - Present. Will Charczuk. All rights reserved.
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository.
     5  
     6  */
     7  
     8  package r2
     9  
    10  import (
    11  	"crypto/tls"
    12  	"crypto/x509"
    13  	"time"
    14  )
    15  
    16  // OptTLSClientConfig sets the tls config for the request.
    17  // It will create a client, and a transport if unset.
    18  func OptTLSClientConfig(cfg *tls.Config) Option {
    19  	return func(r *Request) error {
    20  		transport, err := EnsureHTTPTransport(r)
    21  		if err != nil {
    22  			return err
    23  		}
    24  		transport.TLSClientConfig = cfg
    25  		return nil
    26  	}
    27  }
    28  
    29  // OptTLSInsecureSkipVerify sets if we should skip verification.
    30  func OptTLSInsecureSkipVerify(insecureSkipVerify bool) Option {
    31  	return func(r *Request) error {
    32  		transport, err := EnsureHTTPTransport(r)
    33  		if err != nil {
    34  			return err
    35  		}
    36  		if transport.TLSClientConfig == nil {
    37  			transport.TLSClientConfig = &tls.Config{}
    38  		}
    39  		transport.TLSClientConfig.InsecureSkipVerify = insecureSkipVerify
    40  		return nil
    41  	}
    42  }
    43  
    44  // OptTLSHandshakeTimeout sets the client transport TLSHandshakeTimeout.
    45  func OptTLSHandshakeTimeout(d time.Duration) Option {
    46  	return func(r *Request) error {
    47  		transport, err := EnsureHTTPTransport(r)
    48  		if err != nil {
    49  			return err
    50  		}
    51  		transport.TLSHandshakeTimeout = d
    52  		return nil
    53  	}
    54  }
    55  
    56  // OptTLSRootCAs sets the client tls root ca pool.
    57  func OptTLSRootCAs(pool *x509.CertPool) Option {
    58  	return func(r *Request) error {
    59  		transport, err := EnsureHTTPTransport(r)
    60  		if err != nil {
    61  			return err
    62  		}
    63  		if transport.TLSClientConfig == nil {
    64  			transport.TLSClientConfig = &tls.Config{}
    65  		}
    66  		transport.TLSClientConfig.RootCAs = pool
    67  		return nil
    68  	}
    69  }
    70  
    71  // OptTLSClientCert adds a client certificate to the request.
    72  func OptTLSClientCert(cert tls.Certificate) Option {
    73  	return func(r *Request) error {
    74  		transport, err := EnsureHTTPTransport(r)
    75  		if err != nil {
    76  			return err
    77  		}
    78  		if transport.TLSClientConfig == nil {
    79  			transport.TLSClientConfig = &tls.Config{}
    80  		}
    81  		transport.TLSClientConfig.Certificates = append(transport.TLSClientConfig.Certificates, cert)
    82  		return nil
    83  	}
    84  }