This repository has been archived by the owner on Sep 22, 2022. It is now read-only.
forked from bitrise-steplib/steps-random-quote
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstep.go
144 lines (116 loc) · 3.32 KB
/
step.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"os/exec"
"strings"
"./retry"
)
const (
urlString = "http://api.icndb.com/jokes/random"
)
const (
retryCount = 2
waitTime = 20 //seconds
)
func fail(format string, v ...interface{}) {
errorMsg := fmt.Sprintf(format, v...)
fmt.Printf("\x1b[31;1m%s\x1b[0m\n", errorMsg)
os.Exit(1)
}
func warn(format string, v ...interface{}) {
errorMsg := fmt.Sprintf(format, v...)
fmt.Printf("\x1b[33;1m%s\x1b[0m\n", errorMsg)
}
func info(format string, v ...interface{}) {
fmt.Println()
errorMsg := fmt.Sprintf(format, v...)
fmt.Printf("\x1b[34;1m%s\x1b[0m\n", errorMsg)
}
func details(format string, v ...interface{}) {
errorMsg := fmt.Sprintf(format, v...)
fmt.Printf(" %s\n", errorMsg)
}
func done(format string, v ...interface{}) {
errorMsg := fmt.Sprintf(format, v...)
fmt.Printf(" \x1b[32;1m%s\x1b[0m\n", errorMsg)
}
func exportEnvironmentWithEnvman(keyStr, valueStr string) error {
envman := exec.Command("envman", "add", "--key", keyStr)
envman.Stdin = strings.NewReader(valueStr)
envman.Stdout = os.Stdout
envman.Stderr = os.Stderr
return envman.Run()
}
func main() {
// request
request, err := http.NewRequest("GET", urlString, nil)
if err != nil {
fail("Failed to create requestuest, err: %s", err)
}
request.Header.Add("Accept", "application/json")
request.Header.Add("Content-Type", "application/x-www-form-urlencoded")
// perform request
info("Getting random quote from: %s", urlString)
client := &http.Client{}
var response *http.Response
defer func() {
if response != nil {
if err := response.Body.Close(); err != nil {
warn("Failed to close response body, error: %s", err)
}
}
}()
if err := retry.Times(retryCount).Wait(waitTime).Try(func(attempt uint) error {
var requestErr error
if attempt > 0 {
warn("Retrying...")
}
response, requestErr = client.Do(request)
if requestErr != nil {
warn("%d attempt failed:", attempt)
fmt.Println(requestErr.Error())
}
if response.StatusCode != 200 {
bodyBytes, readErr := ioutil.ReadAll(response.Body)
if readErr != nil {
warn("Failed to read request body, err: %s", err)
requestErr = fmt.Errorf("Request finished with non success status code: (%d)", response.StatusCode)
} else {
requestErr = fmt.Errorf("Request finished with non success status code: (%d), response: (%s)", response.StatusCode, string(bodyBytes))
}
warn("%d attempt failed:", attempt)
fmt.Println(requestErr.Error())
}
return requestErr
}); err != nil {
fail("Failed to perform request, error: %s", err)
}
// Parse body
bodyBytes, err := ioutil.ReadAll(response.Body)
if err != nil {
fail("Failed to read request body, err: %s", err)
}
var data map[string]interface{}
if err = json.Unmarshal(bodyBytes, &data); err != nil {
fail("Failed to unmarshal (%s), err: %s", string(bodyBytes), err)
}
value := data["value"]
valueMap, isKind := value.(map[string]interface{})
if isKind == false {
fail("Failed to convert response: %s", value)
}
joke := valueMap["joke"].(string)
joke, err = url.QueryUnescape(joke)
if err != nil {
fail("Failed to url decode response (%s), err: %s", joke, err)
}
if err := exportEnvironmentWithEnvman("RANDOM_QUOTE", joke); err != nil {
fail("Failed to add output to envman, err: %s", err)
}
done(joke)
}