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