cmd_api.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // Copyright Joyent, Inc.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this
  5. // file, You can obtain one at http://mozilla.org/MPL/2.0/.
  6. package main
  7. import (
  8. "bytes"
  9. "fmt"
  10. "io/ioutil"
  11. "os"
  12. "github.com/jawher/mow.cli"
  13. )
  14. func init() {
  15. App.Command(
  16. "api",
  17. "",
  18. func(cmd *cli.Cmd) {
  19. cmd.Command(
  20. "get",
  21. "Perform an HTTP GET against the provided URL",
  22. func(cmd *cli.Cmd) {
  23. var urlArg = cmd.StringArg("URL", "", "The API path to GET. Must *not* include the hostname or port")
  24. cmd.Spec = "URL"
  25. cmd.Action = func() {
  26. fmt.Println(API.DoBadly(API.Sling().Get(*urlArg)).Body)
  27. }
  28. },
  29. )
  30. cmd.Command(
  31. "delete",
  32. "Perform an HTTP DELETE against the provided URL",
  33. func(cmd *cli.Cmd) {
  34. var urlArg = cmd.StringArg("URL", "", "The API path to DELETE. Must *not* include the hostname or port")
  35. cmd.Spec = "URL"
  36. cmd.Action = func() {
  37. fmt.Println(API.DoBadly(API.Sling().New().Delete(*urlArg)).Body)
  38. }
  39. },
  40. )
  41. cmd.Command(
  42. "post",
  43. "Perform an HTTP POST against the provided URL",
  44. func(cmd *cli.Cmd) {
  45. var (
  46. urlArg = cmd.StringArg("URL", "", "The API path to POST. Must *not* include the hostname or port")
  47. filePathArg = cmd.StringArg("FILE", "-", "Path to a JSON file to use as the request body. '-' indicates STDIN")
  48. )
  49. cmd.Spec = "URL [FILE]"
  50. cmd.Action = func() {
  51. var b []byte
  52. var err error
  53. if *filePathArg == "-" {
  54. b, err = ioutil.ReadAll(os.Stdin)
  55. } else {
  56. b, err = ioutil.ReadFile(*filePathArg)
  57. }
  58. if err != nil {
  59. panic(err)
  60. }
  61. fmt.Println(API.DoBadly(
  62. API.Sling().New().Post(*urlArg).
  63. Set("Content-Type", "application/json").
  64. Body(bytes.NewReader(b)),
  65. ).Body)
  66. }
  67. },
  68. )
  69. cmd.Command(
  70. "version",
  71. "Get the version of the API we are talking to",
  72. func(cmd *cli.Cmd) {
  73. cmd.Action = func() {
  74. if API.JsonOnly {
  75. fmt.Printf("{\"version\":\"%s\"}\n", API.Version())
  76. } else {
  77. fmt.Println(API.Version())
  78. }
  79. }
  80. },
  81. )
  82. },
  83. )
  84. }