-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcs.go
More file actions
78 lines (67 loc) · 1.58 KB
/
cs.go
File metadata and controls
78 lines (67 loc) · 1.58 KB
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
package cs
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"strings"
)
type Step struct {
State string
}
type ReplicaStatus struct {
State string `json:"state"`
Steps []Step `json:"steps"`
Replica string `json:"replica"`
Server string `json:"server"`
}
func GetApiUrl() string {
url := os.Getenv("CS_API")
if url != "" {
return url
}
return "https://codesphere.com/api"
}
func GetPipelineStatus(ws int, stage string) (res []ReplicaStatus, err error) {
status, err := Get(fmt.Sprintf("workspaces/%d/pipeline/%s", ws, stage))
if err != nil {
err = fmt.Errorf("failed to get pipeline status: %e", err)
return
}
err = json.Unmarshal(status, &res)
if err != nil {
err = fmt.Errorf("failed to unmarshal pipeline status: %e", err)
return
}
return
}
func Get(path string) (body []byte, err error) {
req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/%s", GetApiUrl(), strings.TrimPrefix(path, "/")), http.NoBody)
if err != nil {
err = fmt.Errorf("failed to create request: %e", err)
return
}
err = SetAuthoriziationHeader(req)
if err != nil {
err = fmt.Errorf("failed to set header: %e", err)
return
}
res, err := http.DefaultClient.Do(req)
if err != nil {
err = fmt.Errorf("GET failed: %e", err)
return
}
defer func() { _ = res.Body.Close() }()
body, err = io.ReadAll(res.Body)
return
}
func SetAuthoriziationHeader(req *http.Request) error {
apiToken := os.Getenv("CS_TOKEN")
if apiToken == "" {
return errors.New("CS_TOKEN env var required, but not set")
}
req.Header.Set("Authorization", "Bearer "+apiToken)
return nil
}