|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "github.com/urfave/cli/v2" |
| 6 | + "io" |
| 7 | + "log" |
| 8 | + "log/slog" |
| 9 | + "net/http" |
| 10 | + "os" |
| 11 | + "os/exec" |
| 12 | + "path/filepath" |
| 13 | + "strconv" |
| 14 | +) |
| 15 | + |
| 16 | +const apiHost string = "https://http.cat" |
| 17 | + |
| 18 | +func main() { |
| 19 | + app := &cli.App{ |
| 20 | + Name: "http-cat", |
| 21 | + Usage: "Returns a HTTP 🐱 kitty!", |
| 22 | + Action: func(cCtx *cli.Context) error { |
| 23 | + var http_status_code string = cCtx.Args().Get(0) |
| 24 | + |
| 25 | + if !isStringNumber(http_status_code) { |
| 26 | + fmt.Println( |
| 27 | + "You must provide a HTTP status code! " + |
| 28 | + "E.g. http-cat 404, http-cat 500. Run 'http-cat --help' for more help.", |
| 29 | + ) |
| 30 | + return nil |
| 31 | + } |
| 32 | + |
| 33 | + slog.Debug("Making request to HTTP Cat API...") |
| 34 | + |
| 35 | + response, err := http.Get(apiHost + "/" + http_status_code) |
| 36 | + |
| 37 | + if err != nil { |
| 38 | + log.Fatalln("GET request to HTTP Cat API failed:", err) |
| 39 | + } |
| 40 | + |
| 41 | + var temp_directory_path string = getTempDir() |
| 42 | + |
| 43 | + if _, err := os.Stat(temp_directory_path); os.IsNotExist(err) { |
| 44 | + _ = os.Mkdir(temp_directory_path, 0777) // everyone can read and write |
| 45 | + } |
| 46 | + |
| 47 | + var path_to_image string = filepath.Join(getTempDir(), "kitty.jpeg") |
| 48 | + |
| 49 | + body, err := io.ReadAll(response.Body) |
| 50 | + if err != nil { |
| 51 | + log.Fatalln("Failed to read image from API:", err) |
| 52 | + } |
| 53 | + |
| 54 | + err = os.WriteFile(path_to_image, body, 0777) |
| 55 | + |
| 56 | + if err != nil { |
| 57 | + log.Fatalln("Failed to write the 🐈 kitty in the temp directory:", err) |
| 58 | + } |
| 59 | + |
| 60 | + output, err := exec.Command("chafa", path_to_image, "--scale", "0.7").Output() |
| 61 | + |
| 62 | + if err != nil { |
| 63 | + log.Fatalln( |
| 64 | + "Failed to execute chafa to display 🐈 kitty! "+ |
| 65 | + "Make sure you have it installed and in path. Error:", err, |
| 66 | + ) |
| 67 | + } |
| 68 | + |
| 69 | + fmt.Print(string(output)) |
| 70 | + |
| 71 | + return nil |
| 72 | + }, |
| 73 | + } |
| 74 | + |
| 75 | + if err := app.Run(os.Args); err != nil { |
| 76 | + log.Fatal(err) |
| 77 | + } |
| 78 | +} |
| 79 | + |
| 80 | +func isStringNumber(string string) bool { |
| 81 | + if _, err := strconv.Atoi(string); err == nil { |
| 82 | + return true |
| 83 | + } |
| 84 | + |
| 85 | + return false |
| 86 | +} |
| 87 | + |
| 88 | +// Currently only supports Linux, fuck you Windows, no kitties for you for the time being. |
| 89 | +func getTempDir() string { |
| 90 | + var temp_directory string = os.Getenv("TMPDIR") |
| 91 | + |
| 92 | + if temp_directory == "" { |
| 93 | + temp_directory = "/tmp" |
| 94 | + } |
| 95 | + |
| 96 | + return filepath.Join(temp_directory, "http-cat") |
| 97 | +} |
0 commit comments