9
"github.com/pkg/errors"
11
error_types "github.com/kumahq/kuma/pkg/core/rest/errors/types"
12
util_http "github.com/kumahq/kuma/pkg/util/http"
15
type TokenClient struct {
16
client util_http.Client
20
func NewTokenClient(client util_http.Client, entity string) TokenClient {
23
url: "/tokens/" + entity,
27
func (tc TokenClient) Generate(tokenReq any) (string, error) {
28
reqBytes, err := json.Marshal(tokenReq)
30
return "", errors.Wrap(err, "could not marshal token request to json")
32
req, err := http.NewRequest(http.MethodPost, tc.url, bytes.NewReader(reqBytes))
34
return "", errors.Wrap(err, "could not construct the request")
36
req.Header.Set("content-type", "application/json")
37
resp, err := tc.client.Do(req)
39
return "", errors.Wrap(err, "could not execute the request")
41
defer resp.Body.Close()
42
body, err := io.ReadAll(resp.Body)
44
return "", errors.Wrap(err, "could not read a body of the request")
46
if resp.StatusCode != http.StatusOK {
47
var kumaErr error_types.Error
48
if err := json.Unmarshal(body, &kumaErr); err == nil {
49
if kumaErr.Title != "" {
53
return "", errors.Errorf("(%d): %s", resp.StatusCode, body)
55
return string(body), nil