-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
107 lines (91 loc) · 2.21 KB
/
main.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
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"io"
"log"
"net/http"
"os"
"time"
)
const (
version = "1.2"
)
var (
printVersion = flag.Bool("v", false, "Shows program version")
returnRaw = flag.Bool("r", false, "Returns link to raw content")
hasteURL = flag.String("d", "https://haste.zneix.eu", "Hastebin server's URL to which data will be uploaded")
apiRoute = "/documents"
httpClient = &http.Client{
Timeout: 10 * time.Second,
}
)
func readStdin() {
stdinBuffer, _ := io.ReadAll(os.Stdin)
content := string(stdinBuffer)
uploadToHaste(*hasteURL, content)
}
func uploadToHaste(url, data string) {
type HasteResponseData struct {
Key string `json:"key,omitempty"`
}
req, err := http.NewRequest("POST", *hasteURL+apiRoute, bytes.NewBufferString(data))
if err != nil {
log.Fatal("Error while creating HTTP request:", err)
return
}
req.Header.Set("User-Agent", fmt.Sprintf("haste-client/%s", version))
// Send the request
resp, err := httpClient.Do(req)
if err != nil {
log.Fatal("Error while performing the request:", err)
return
}
defer resp.Body.Close()
if resp.StatusCode < http.StatusOK || resp.StatusCode > http.StatusMultipleChoices {
log.Fatalln("Failed to upload data, server responded with", resp.StatusCode)
return
}
// Error out if the invite isn't found or something else went wrong with the request
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatalln("Error while reading response:", err)
return
}
jsonResponse := new(HasteResponseData)
if err := json.Unmarshal(body, jsonResponse); err != nil {
log.Fatalln("Error while unmarshaling JSON response:", err)
return
}
var finalURL = url
if *returnRaw {
finalURL += "/raw"
}
finalURL += "/" + jsonResponse.Key
fmt.Println(finalURL)
}
func main() {
// Handle CLI arguments
flag.Parse()
if *printVersion {
fmt.Printf("Haste Client %s\n", version)
return
}
if len(os.Args) == 1 {
readStdin()
} else {
for _, file := range os.Args[1:] {
if file == "-" {
readStdin()
} else {
data, err := os.ReadFile(file)
if err != nil {
log.Fatalf("%s: Failed reading data from file: %s\n", os.Args[0], err)
}
uploadToHaste(*hasteURL, string(data))
}
}
}
}