summaryrefslogtreecommitdiffstats
path: root/client/go/cmd/curl.go
blob: 2496ddc3abcf7de1c7a574fdc422cc0a88844983 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package cmd

import (
	"log"
	"os"
	"strings"

	"github.com/spf13/cobra"
	"github.com/vespa-engine/vespa/client/go/curl"
)

var curlDryRun bool

func init() {
	rootCmd.AddCommand(curlCmd)
	curlCmd.Flags().BoolVarP(&curlDryRun, "dry-run", "n", false, "Print the curl command that would be executed")
}

var curlCmd = &cobra.Command{
	Use:   "curl [curl-options] path",
	Short: "Query Vespa using curl",
	Long: `Query Vespa using curl.

Execute curl with the appropriate URL, certificate and private key for your application.`,
	Example: `$ vespa curl /search/?yql=query
$ vespa curl -- -v --data-urlencode "yql=select * from sources * where title contains 'foo';" /search/
$ vespa curl -t local -- -v /search/?yql=query
`,
	DisableAutoGenTag: true,
	Args:              cobra.MinimumNArgs(1),
	Run: func(cmd *cobra.Command, args []string) {
		cfg, err := LoadConfig()
		if err != nil {
			fatalErr(err, "Could not load config")
			return
		}
		app := getApplication()
		privateKeyFile, err := cfg.PrivateKeyPath(app)
		if err != nil {
			fatalErr(err)
			return
		}
		certificateFile, err := cfg.CertificatePath(app)
		if err != nil {
			fatalErr(err)
			return
		}
		service := getService("query", 0, "")
		url := joinURL(service.BaseURL, args[len(args)-1])
		rawArgs := args[:len(args)-1]
		c, err := curl.RawArgs(url, rawArgs...)
		if err != nil {
			fatalErr(err)
			return
		}
		c.PrivateKey = privateKeyFile
		c.Certificate = certificateFile

		if curlDryRun {
			log.Print(c.String())
		} else {
			if err := c.Run(os.Stdout, os.Stderr); err != nil {
				fatalErr(err, "Failed to run curl")
				return
			}
		}
	},
}

func joinURL(baseURL, path string) string {
	baseURL = strings.TrimSuffix(baseURL, "/")
	path = strings.TrimPrefix(path, "/")
	return baseURL + "/" + path
}