package cli import ( "encoding/json" "errors" "fmt" "io" "net/http" "strings" "github.com/annybs/shorty/internal/types" ) type ListCmd struct { AllPath string `help:"All-path (SHORTY_ALL_PATH)" default:"${all_path}"` Token string `short:"t" help:"Bearer token (SHORTY_TOKEN)" default:"${token}"` URL string `short:"u" help:"Shorty URL (SHORTY_URL)" default:"${url}"` } func (c *ListCmd) Run(ctx *Context) error { url := strings.Join([]string{c.URL, c.AllPath}, "") req, err := http.NewRequest(http.MethodGet, url, nil) if err != nil { return err } if c.Token != "" { req.Header.Add("authorization", fmt.Sprintf("bearer %s", c.Token)) } res, err := http.DefaultClient.Do(req) if err != nil { return err } if res.StatusCode != http.StatusOK { body, err := io.ReadAll(res.Body) if err != nil { return err } if len(body) > 0 { return errors.New(string(body)) } return errors.New(res.Status) } body, err := io.ReadAll(res.Body) if err != nil { return err } data := map[string]*types.Redirect{} if err := json.Unmarshal(body, &data); err != nil { return err } for from, redirect := range data { fmt.Printf("%s %d %s\n", from, redirect.StatusCode, redirect.Destination) } return nil }