github.com/DaAlbrecht/cf-cli@v0.0.0-20231128151943-1fe19bb400b9/actor/v7action/curl.go (about) 1 package v7action 2 3 import ( 4 "bufio" 5 "fmt" 6 "io/ioutil" 7 "net/http" 8 "net/textproto" 9 "strings" 10 11 "code.cloudfoundry.org/cli/command/translatableerror" 12 ) 13 14 func (actor Actor) MakeCurlRequest( 15 method string, 16 path string, 17 customHeaders []string, 18 data string, 19 failOnHTTPError bool, 20 ) ([]byte, *http.Response, error) { 21 url := fmt.Sprintf("%s/%s", actor.Config.Target(), strings.TrimLeft(path, "/")) 22 23 requestHeaders, err := buildRequestHeaders(customHeaders) 24 if err != nil { 25 return nil, nil, translatableerror.RequestCreationError{Err: err} 26 } 27 28 if method == "" && data != "" { 29 method = "POST" 30 } 31 32 requestBodyBytes := []byte(data) 33 34 trimmedData := strings.Trim(string(data), `"'`) 35 if strings.HasPrefix(trimmedData, "@") { 36 trimmedData = strings.Trim(trimmedData[1:], `"'`) 37 requestBodyBytes, err = ioutil.ReadFile(trimmedData) 38 if err != nil { 39 return nil, nil, translatableerror.RequestCreationError{Err: err} 40 } 41 } 42 43 responseBody, httpResponse, err := actor.CloudControllerClient.MakeRequestSendReceiveRaw( 44 method, 45 url, 46 requestHeaders, 47 requestBodyBytes, 48 ) 49 50 if err != nil && failOnHTTPError { 51 return nil, nil, translatableerror.CurlExit22Error{StatusCode: httpResponse.StatusCode} 52 } 53 54 return responseBody, httpResponse, nil 55 } 56 57 func buildRequestHeaders(customHeaders []string) (http.Header, error) { 58 headerString := strings.Join(customHeaders, "\n") 59 headerString = strings.TrimSpace(headerString) 60 headerString += "\n\n" 61 62 headerReader := bufio.NewReader(strings.NewReader(headerString)) 63 parsedCustomHeaders, err := textproto.NewReader(headerReader).ReadMIMEHeader() 64 if err != nil { 65 return nil, err 66 } 67 68 return http.Header(parsedCustomHeaders), nil 69 }