-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathutil.go
More file actions
106 lines (92 loc) · 2.24 KB
/
util.go
File metadata and controls
106 lines (92 loc) · 2.24 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
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
package cmd
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strings"
"github.com/codesphere-cloud/cs-go/pkg/api"
)
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 GetApiToken() (string, error) {
apiToken := os.Getenv("CS_TOKEN")
if apiToken == "" {
return "", errors.New("CS_TOKEN env var required, but not set")
}
return apiToken, nil
}
func SetAuthoriziationHeader(req *http.Request) error {
token, err := GetApiToken()
if err != nil {
return fmt.Errorf("failed to get API token: %e", err)
}
req.Header.Set("Authorization", "Bearer "+token)
return nil
}
func NewClient(opts GlobalOptions) (*api.Client, error) {
token, err := GetApiToken()
if err != nil {
return nil, fmt.Errorf("failed to get API token: %e", err)
}
apiUrl, err := url.Parse(opts.GetApiUrl())
if err != nil {
return nil, fmt.Errorf("failed to parse URL '%s': %e", opts.GetApiUrl(), err)
}
client := api.NewClient(context.Background(), api.Configuration{
BaseUrl: apiUrl,
Token: token,
})
return client, nil
}