add.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package cli
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "strings"
  8. )
  9. type AddCmd struct {
  10. Token string `short:"t" help:"Bearer token (SHORTY_TOKEN)" default:"${token}"`
  11. URL string `short:"u" help:"Shorty URL (SHORTY_URL)" default:"${url}"`
  12. Path string `arg:"" help:"Redirect path"`
  13. Destination string `arg:"" help:"Destination URL"`
  14. }
  15. func (c *AddCmd) Run(ctx *Context) error {
  16. url := strings.Join([]string{c.URL, c.Path}, "")
  17. req, err := http.NewRequest(http.MethodPut, url, strings.NewReader(c.Destination))
  18. if err != nil {
  19. return err
  20. }
  21. if c.Token != "" {
  22. req.Header.Add("authorization", fmt.Sprintf("bearer %s", c.Token))
  23. }
  24. res, err := http.DefaultClient.Do(req)
  25. if err != nil {
  26. return err
  27. }
  28. if res.StatusCode != http.StatusOK {
  29. body, err := io.ReadAll(res.Body)
  30. if err != nil {
  31. return err
  32. }
  33. if len(body) > 0 {
  34. return errors.New(string(body))
  35. }
  36. return errors.New(res.Status)
  37. }
  38. return nil
  39. }
  40. func (c *AddCmd) Validate() error {
  41. if len(c.Path) < 1 || c.Path[0] != '/' {
  42. return errors.New("invalid <path>")
  43. }
  44. return nil
  45. }