-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcli_session.go
75 lines (59 loc) · 1.7 KB
/
cli_session.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
package fly
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
)
type CLISession struct {
ID string `json:"id"`
URL string `json:"auth_url,omitempty"`
AccessToken string `json:"access_token,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
// StartCLISession starts a session with the platform via web
func StartCLISession(sessionName string, args map[string]interface{}) (CLISession, error) {
var result CLISession
if args == nil {
args = make(map[string]interface{})
}
args["name"] = sessionName
postData, _ := json.Marshal(args)
url := fmt.Sprintf("%s/api/v1/cli_sessions", baseURL)
resp, err := http.Post(url, "application/json", bytes.NewBuffer(postData))
if err != nil {
return result, err
}
if resp.StatusCode != 201 {
return result, ErrUnknown
}
defer resp.Body.Close() //skipcq: GO-S2307
json.NewDecoder(resp.Body).Decode(&result)
return result, nil
}
func GetCLISessionState(ctx context.Context, id string) (CLISession, error) {
var value CLISession
url := fmt.Sprintf("%s/api/v1/cli_sessions/%s", baseURL, id)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return value, err
}
res, err := http.DefaultClient.Do(req)
if err != nil {
return value, err
}
defer res.Body.Close() //skipcq: GO-S2307
switch res.StatusCode {
case http.StatusOK:
var auth CLISession
if err = json.NewDecoder(res.Body).Decode(&auth); err != nil {
return value, fmt.Errorf("failed to decode session, please try again: %w", err)
}
return auth, nil
case http.StatusNotFound:
return value, ErrNotFound
default:
return value, ErrUnknown
}
}