get.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package cli
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "strings"
  8. )
  9. type GetCmd struct {
  10. URL string `short:"u" help:"Shorty URL (SHORTY_URL)" default:"${url}"`
  11. Path string `arg:"" help:"Redirect path"`
  12. }
  13. func (c *GetCmd) Run(ctx *Context) error {
  14. url := strings.Join([]string{c.URL, c.Path}, "")
  15. req, err := http.NewRequest(http.MethodGet, url, nil)
  16. if err != nil {
  17. return err
  18. }
  19. // Create a specialized client that ignores redirection
  20. client := &http.Client{
  21. CheckRedirect: func(*http.Request, []*http.Request) error {
  22. return http.ErrUseLastResponse
  23. },
  24. }
  25. res, err := client.Do(req)
  26. if err != nil {
  27. return err
  28. }
  29. if res.StatusCode == http.StatusNotFound {
  30. return nil
  31. } else if res.StatusCode != http.StatusPermanentRedirect {
  32. body, err := io.ReadAll(res.Body)
  33. if err != nil {
  34. return err
  35. }
  36. if len(body) > 0 {
  37. return errors.New(string(body))
  38. }
  39. return errors.New(res.Status)
  40. }
  41. dest := res.Header.Get("location")
  42. fmt.Println(dest)
  43. return nil
  44. }
  45. func (c *GetCmd) Validate() error {
  46. if len(c.Path) < 1 || c.Path[0] != '/' {
  47. return errors.New("invalid <path>")
  48. }
  49. return nil
  50. }