go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/r2/opt_check_redirect.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 "net/http"
    11  
    12  // OptCheckRedirect sets the client check redirect function.
    13  func OptCheckRedirect(checkfn func(r *http.Request, via []*http.Request) error) Option {
    14  	return func(r *Request) error {
    15  		if r.client == nil {
    16  			r.client = &http.Client{}
    17  		}
    18  		r.client.CheckRedirect = checkfn
    19  		return nil
    20  	}
    21  }
    22  
    23  // OptMaxRedirects tells the http client to only follow a given
    24  // number of redirects, overriding the standard library default of 10.
    25  // Use the companion helper `ErrIsTooManyRedirects` to test if the returned error
    26  // from a call indicates the redirect limit was reached.
    27  func OptMaxRedirects(maxRedirects int) Option {
    28  	return func(r *Request) error {
    29  		if r.client == nil {
    30  			r.client = &http.Client{}
    31  		}
    32  		r.client.CheckRedirect = func(r *http.Request, via []*http.Request) error {
    33  			if len(via) >= maxRedirects {
    34  				return http.ErrUseLastResponse
    35  			}
    36  			return nil
    37  		}
    38  		return nil
    39  	}
    40  }