示例#1
0
文件: curl.go 项目: fujitsu-cf/cli
func (cmd *Curl) Execute(c flags.FlagContext) error {
	path := c.Args()[0]
	headers := c.StringSlice("H")

	var method string
	var body string

	if c.IsSet("d") {
		method = "POST"

		jsonBytes, err := util.GetContentsFromOptionalFlagValue(c.String("d"))
		if err != nil {
			return err
		}
		body = string(jsonBytes)
	}

	if c.IsSet("X") {
		method = c.String("X")
	}

	reqHeader := strings.Join(headers, "\n")

	responseHeader, responseBody, apiErr := cmd.curlRepo.Request(method, path, reqHeader, body)
	if apiErr != nil {
		return errors.New(T("Error creating request:\n{{.Err}}", map[string]interface{}{"Err": apiErr.Error()}))
	}

	if trace.LoggingToStdout && !cmd.pluginCall {
		return nil
	}

	if c.Bool("i") {
		cmd.ui.Say(responseHeader)
	}

	if c.String("output") != "" {
		err := cmd.writeToFile(responseBody, c.String("output"))
		if err != nil {
			return errors.New(T("Error creating request:\n{{.Err}}", map[string]interface{}{"Err": err}))
		}
	} else {
		if strings.Contains(responseHeader, "application/json") {
			buffer := bytes.Buffer{}
			err := json.Indent(&buffer, []byte(responseBody), "", "   ")
			if err == nil {
				responseBody = buffer.String()
			}
		}

		cmd.ui.Say(responseBody)
	}
	return nil
}
import (
	"fmt"
	"os"

	"code.cloudfoundry.org/cli/cf/util"

	"code.cloudfoundry.org/gofileutils/fileutils"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("Flag Content Helpers", func() {
	Describe("GetContentsFromOptionalFlagValue", func() {
		It("returns an empty byte slice when given an empty string", func() {
			bs, err := util.GetContentsFromOptionalFlagValue("")
			Expect(err).NotTo(HaveOccurred())
			Expect(bs).To(Equal([]byte{}))
		})

		It("returns bytes when given a file name prefixed with @", func() {
			fileutils.TempFile("get-data-test", func(tmpFile *os.File, err error) {
				fileData := `{"foo": "bar"}`
				tmpFile.WriteString(fileData)

				bs, err := util.GetContentsFromOptionalFlagValue("@" + tmpFile.Name())
				Expect(err).NotTo(HaveOccurred())
				Expect(bs).To(Equal([]byte(fileData)))
			})
		})