github.com/wanddynosios/cli/v8@v8.7.9-0.20240221182337-1a92e3a7017f/api/cloudcontroller/ccv3/request.go (about)

     1  package ccv3
     2  
     3  import (
     4  	"io"
     5  	"net/http"
     6  
     7  	"code.cloudfoundry.org/cli/api/cloudcontroller"
     8  	"code.cloudfoundry.org/cli/api/cloudcontroller/ccv3/internal"
     9  )
    10  
    11  // requestOptions contains all the options to create an HTTP request.
    12  type requestOptions struct {
    13  	// URIParams are the list URI route parameters
    14  	URIParams internal.Params
    15  
    16  	// Query is a list of HTTP query parameters. Query will overwrite any
    17  	// existing query string in the URI. If you want to preserve the query
    18  	// string in URI make sure Query is nil.
    19  	Query []Query
    20  
    21  	// RequestName is the name of the request (see routes)
    22  	RequestName string
    23  	// Header contains custom headers to pass to the request.
    24  	Header http.Header
    25  	// Method is the HTTP method.
    26  	Method string
    27  	// URL is the request path.
    28  	URL string
    29  	// Body is the content of the request.
    30  	Body io.ReadSeeker
    31  }
    32  
    33  // newHTTPRequest returns a constructed HTTP.Request with some defaults.
    34  // Defaults are applied when Request options are not filled in.
    35  func (requester *RealRequester) newHTTPRequest(passedRequest requestOptions) (*cloudcontroller.Request, error) {
    36  	var request *http.Request
    37  	var err error
    38  	if passedRequest.URL != "" {
    39  		request, err = http.NewRequest(
    40  			passedRequest.Method,
    41  			passedRequest.URL,
    42  			passedRequest.Body,
    43  		)
    44  	} else {
    45  		request, err = requester.router.CreateRequest(
    46  			passedRequest.RequestName,
    47  			map[string]string(passedRequest.URIParams),
    48  			passedRequest.Body,
    49  		)
    50  	}
    51  	if err != nil {
    52  		return nil, err
    53  	}
    54  
    55  	if passedRequest.Query != nil {
    56  		request.URL.RawQuery = FormatQueryParameters(passedRequest.Query).Encode()
    57  	}
    58  
    59  	request.Header = http.Header{}
    60  	if passedRequest.Header != nil {
    61  		request.Header = passedRequest.Header
    62  	}
    63  
    64  	if request.Header.Get("User-Agent") == "" {
    65  		request.Header.Set("User-Agent", requester.userAgent)
    66  	}
    67  
    68  	if request.Header.Get("Accept") == "" {
    69  		request.Header.Set("Accept", "application/json")
    70  	}
    71  
    72  	if request.Header.Get("Content-Type") == "" {
    73  		request.Header.Set("Content-Type", "application/json")
    74  	}
    75  
    76  	return cloudcontroller.NewRequest(request, passedRequest.Body), nil
    77  }