github.com/LukasHeimann/cloudfoundrycli/v8@v8.4.4/command/v7/curl_command.go (about) 1 package v7 2 3 import ( 4 "io/ioutil" 5 "net/http/httputil" 6 7 "github.com/LukasHeimann/cloudfoundrycli/v8/command/flag" 8 "github.com/LukasHeimann/cloudfoundrycli/v8/command/translatableerror" 9 ) 10 11 type CurlCommand struct { 12 BaseCommand 13 14 RequiredArgs flag.APIPath `positional-args:"yes"` 15 CustomHeaders []string `short:"H" description:"Custom headers to include in the request, flag can be specified multiple times"` 16 HTTPMethod string `short:"X" description:"HTTP method (GET,POST,PUT,DELETE,etc)"` 17 HTTPData flag.PathWithAt `short:"d" description:"HTTP data to include in the request body, or '@' followed by a file name to read the data from"` 18 FailOnHTTPError bool `short:"f" long:"fail" description:"Server errors return exit code 22"` 19 IncludeReponseHeaders bool `short:"i" description:"Include response headers in the output"` 20 OutputFile flag.Path `long:"output" description:"Write curl body to FILE instead of stdout"` 21 usage interface{} `usage:"CF_NAME curl PATH [-iv] [-X METHOD] [-H HEADER]... [-d DATA] [--output FILE]\n\n By default 'CF_NAME curl' will perform a GET to the specified PATH. If data\n is provided via -d, a POST will be performed instead, and the Content-Type\n will be set to application/json. You may override headers with -H and the\n request method with -X.\n\n For API documentation, please visit http://apidocs.cloudfoundry.org.\n\nEXAMPLES:\n CF_NAME curl \"/v2/apps\" -X GET -H \"Content-Type: application/x-www-form-urlencoded\" -d 'q=name:myapp'\n CF_NAME curl \"/v2/apps\" -d @/path/to/file"` 22 } 23 24 func (cmd CurlCommand) Execute(args []string) error { 25 responseBodyBytes, httpResponse, err := cmd.Actor.MakeCurlRequest( 26 cmd.HTTPMethod, 27 cmd.RequiredArgs.Path, 28 cmd.CustomHeaders, 29 string(cmd.HTTPData), 30 cmd.FailOnHTTPError, 31 ) 32 33 if err != nil { 34 return err 35 } 36 37 if alreadyWroteVerboseOutput, _ := cmd.Config.Verbose(); alreadyWroteVerboseOutput { 38 return nil 39 } 40 41 var bytesToWrite []byte 42 43 if cmd.IncludeReponseHeaders { 44 headerBytes, _ := httputil.DumpResponse(httpResponse, false) 45 bytesToWrite = append(bytesToWrite, headerBytes...) 46 } 47 48 bytesToWrite = append(bytesToWrite, responseBodyBytes...) 49 50 if cmd.OutputFile != "" { 51 err = ioutil.WriteFile(cmd.OutputFile.String(), bytesToWrite, 0666) 52 if err != nil { 53 return translatableerror.FileCreationError{Err: err} 54 } 55 56 cmd.UI.DisplayOK() 57 } else { 58 cmd.UI.DisplayText(string(bytesToWrite)) 59 } 60 61 return nil 62 }