api

package
v1.70.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 5, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var APICmd = base.Cmd{
	BaseCobraCommand: func(_ hcapi2.Client) *cobra.Command {
		cmd := &cobra.Command{
			Use:   "api [options] <path>",
			Short: "Make API call",
		}

		cmd.Flags().StringP("method", "X", "GET", "HTTP method to use for API call")
		_ = cmd.RegisterFlagCompletionFunc("method", cmpl.SuggestCandidates("GET", "POST", "PUT", "DELETE"))

		cmd.Flags().StringP("data", "d", "", "HTTP request body content (use - to read from stdin)")
		cmd.Flags().StringToStringP("value", "v", nil, "key=value pairs to pass as query parameters")
		return cmd
	},
	Run: func(s state.State, cmd *cobra.Command, args []string) error {
		path := args[0]
		method, _ := cmd.Flags().GetString("method")
		data, _ := cmd.Flags().GetString("data")
		values, _ := cmd.Flags().GetStringToString("value")

		method = strings.ToUpper(method)
		switch method {
		case http.MethodGet, http.MethodHead, http.MethodPost,
			http.MethodPut, http.MethodPatch, http.MethodDelete,
			http.MethodConnect, http.MethodOptions, http.MethodTrace:
			break
		default:
			return fmt.Errorf("unknown HTTP method: %s", method)
		}

		var body io.Reader
		switch data {
		case "":
			body = nil
		case "-":
			body = os.Stdin
		default:
			body = strings.NewReader(data)
		}

		if !strings.HasPrefix(path, "/") {
			path = "/" + path
		}

		u, err := url.Parse(path)
		if err != nil {
			return err
		}

		params := u.Query()
		for k, v := range values {
			params.Set(k, v)
		}
		u.RawQuery = params.Encode()

		req, err := s.Client().NewRequest(s, method, u.String(), body)
		if err != nil {
			return err
		}

		var respBuf bytes.Buffer
		_, err = s.Client().Do(req, &respBuf)
		if err != nil {
			return err
		}
		respBody := respBuf.Bytes()

		if json.Valid(respBody) {
			var formatted bytes.Buffer
			if err := json.Indent(&formatted, respBody, "", "  "); err != nil {
				return err
			}
			cmd.Println(formatted.String())
		} else if len(respBody) > 0 {
			cmd.Println(string(respBody))
		}
		return nil
	},
}

Functions

This section is empty.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL