-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
113 lines (98 loc) · 2.47 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
108
109
110
111
112
113
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"github.com/fatih/color"
comment "github.com/sachasmart/terrafir-github-action/github"
"github.com/sachasmart/terrafir-github-action/types"
)
var (
apiKey = getEnv("INPUT_APIKEY", "")
email = getEnv("INPUT_EMAIL", "")
path = getEnv("INPUT_PATH", "")
verboseMode = getEnv("verboseMode", "")
ghToken = getEnv("INPUT_GH-TOKEN", "")
)
func getEnv(key, defaultValue string) string {
fmt.Println(os.Environ())
value := os.Getenv(key)
if value == "" {
fmt.Print("Using default value for ", key, ": ", defaultValue, "\n")
return defaultValue
}
return value
}
func main() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
preRequestCheck()
sendRequest(apiKey, email)
comment.AddComment()
}
func preRequestCheck() {
response, err := http.Get(types.URL)
if err != nil {
log.Fatal(err)
}
defer response.Body.Close()
if response.StatusCode != 200 {
log.Fatal("API is not available")
}
color.Green(fmt.Sprintf("API is available %s", response.Status))
}
func sendRequest(apiKey string, email string) map[string]interface{} {
color.Green(fmt.Sprintf("Using input file: %s", "./input.json"))
payload := &bytes.Buffer{}
writer := multipart.NewWriter(payload)
file, errFile1 := os.Open("./input.json")
if errFile1 != nil {
log.Panic(errFile1)
}
defer file.Close()
part1, _ := writer.CreateFormFile("plan", filepath.Base("./input.json"))
_, errFile1 = io.Copy(part1, file)
if errFile1 != nil {
log.Panic(errFile1)
}
err := writer.Close()
if err != nil {
log.Panic(err)
}
client := &http.Client{}
req, err := http.NewRequest("POST", fmt.Sprintf("%s/assessment/api", types.URL), payload)
if err != nil {
log.Panic(err)
}
req.Header.Add("email", email)
req.Header.Add("Authorization", apiKey)
req.Header.Set("Content-Type", writer.FormDataContentType())
res, err := client.Do(req)
if err != nil {
log.Panic(err)
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
log.Panic(err)
}
fBody, error := formattedBody(body)
if error != nil {
log.Panic("Error formatting body")
}
return fBody
}
func formattedBody(body []byte) (fBody map[string]interface{}, error error) {
var formattedBody map[string]interface{}
if err := json.Unmarshal(body, &formattedBody); err != nil {
log.Println("Error unmarshalling JSON:", err)
return nil, err
}
log.Println(formattedBody)
return formattedBody, nil
}