-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp_lib.go
84 lines (65 loc) · 2.01 KB
/
http_lib.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
package main
import (
"net/http"
"time"
"os"
"encoding/json"
"io"
"fmt"
)
var slackToken = os.Getenv("SLACK_TOKEN")
var slackUrl = os.Getenv("SLACK_URL")
type slackEmojiResp struct {
Ok bool `json:"ok"`
Emoji map[string]string `json:"emoji"`
Cache_ts string `json:"cache_ts"`
}
func httpClient() *http.Client {
client := &http.Client{Timeout: 10 * time.Second}
return client
}
func httpDownloadEmoji(client *http.Client, filepath string, url string) error {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return fmt.Errorf("httpDownloadEmoji - Unable to forge GET request: %w", err)
}
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("httpDownloadEmoji - Unable to downlowd: %w", err)
}
defer resp.Body.Close()
dirpath := dirDefinePath(filepath)
if _, err := os.Stat(dirpath); os.IsNotExist(err) {
if err := os.MkdirAll(dirpath, os.ModePerm); err != nil {
return fmt.Errorf("httpDownloadEmoji - Unable to create directory: %w", err)
}
}
out, err := os.Create(filepath)
if err != nil {
return fmt.Errorf("httpDownloadEmoji - Unable to write file locally: %w", err)
}
defer out.Close()
if _, err = io.Copy(out, resp.Body); err != nil {
return fmt.Errorf("httpDownloadEmoji - Unable to finish writing file locally: %w", err)
}
return nil
}
func httpGetListEmojis(client *http.Client) (map[string]string, error) {
req, err := http.NewRequest("GET", slackUrl + "/api/emoji.list", nil)
if err != nil {
return nil, fmt.Errorf("httpGetListEmojis - Unable to forge GET request: %w", err)
}
req.Header.Add("Authorization", "Bearer " + slackToken)
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("httpGetListEmojis - Unable to process GET: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("httpGetListEmojis - Unable to read response body: %w", err)
}
var target slackEmojiResp
json.Unmarshal(body, &target)
return target.Emoji, nil
}