-
Notifications
You must be signed in to change notification settings - Fork 5
/
session_requests.go
88 lines (70 loc) · 2.58 KB
/
session_requests.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
package se2
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"github.com/pkg/errors"
)
const pathCreateTenantSession = pathTenantByName + "/session"
// createSessionRequest is an internal struct to help with converting data into a json payload we can send against the
// API.
type createSessionRequest struct {
Plugin string `json:"fn"`
Namespace string `json:"namespace"`
}
// CreateSessionResponse has a token inside of it. This token is used in queries against the builder service. Those
// methods will require one of their parameters to be of this type.
type CreateSessionResponse struct {
Token string `json:"token"`
}
// CreateSession will create a session for a given tenant, namespace, and plugin to be used in the builder. You should
// keep track of the return argument and reuse it in later requests.
func (c *Client) CreateSession(ctx context.Context, tenantName, namespace, plugin string) (CreateSessionResponse, error) {
// Check arguments.
if tenantName == emptyString {
return CreateSessionResponse{}, errors.New("client.CreateSession: tenant name cannot be blank")
}
if namespace == emptyString {
return CreateSessionResponse{}, errors.New("client.CreateSession: namespace cannot be blank")
}
if plugin == emptyString {
return CreateSessionResponse{}, errors.New("client.CreateSession: plugin cannot be blank")
}
// Build a body, Dr. Frankenstein!
var body bytes.Buffer
err := json.NewEncoder(&body).Encode(createSessionRequest{
Plugin: plugin,
Namespace: namespace,
})
if err != nil {
return CreateSessionResponse{}, errors.Wrap(err, "client.CreateSession: json.NewEncoder().Encode")
}
// Create the request with the body.
req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf(c.host+pathCreateTenantSession, tenantName), &body)
if err != nil {
return CreateSessionResponse{}, errors.Wrap(err, "client.CreateSession: http.NewRequest")
}
// Do the request.
res, err := c.do(req)
if err != nil {
return CreateSessionResponse{}, errors.Wrap(err, "client.CreateSession: c.do")
}
defer func() {
_ = res.Body.Close()
}()
// Check response code.
if res.StatusCode != http.StatusCreated {
return CreateSessionResponse{}, fmt.Errorf(httpResponseCodeErrorFormat, "client.CreateSession", http.StatusCreated, res.StatusCode)
}
// Marshal response body into what we need to give back.
var t CreateSessionResponse
dec := json.NewDecoder(res.Body)
dec.DisallowUnknownFields()
err = dec.Decode(&t)
if err != nil {
return CreateSessionResponse{}, errors.Wrap(err, "client.CreateSession: dec.Decode")
}
return t, nil
}