kuma

Форк
0
/
client.go 
56 строк · 1.4 Кб
1
package tokens
2

3
import (
4
	"bytes"
5
	"encoding/json"
6
	"io"
7
	"net/http"
8

9
	"github.com/pkg/errors"
10

11
	error_types "github.com/kumahq/kuma/pkg/core/rest/errors/types"
12
	util_http "github.com/kumahq/kuma/pkg/util/http"
13
)
14

15
type TokenClient struct {
16
	client util_http.Client
17
	url    string
18
}
19

20
func NewTokenClient(client util_http.Client, entity string) TokenClient {
21
	return TokenClient{
22
		client: client,
23
		url:    "/tokens/" + entity,
24
	}
25
}
26

27
func (tc TokenClient) Generate(tokenReq any) (string, error) {
28
	reqBytes, err := json.Marshal(tokenReq)
29
	if err != nil {
30
		return "", errors.Wrap(err, "could not marshal token request to json")
31
	}
32
	req, err := http.NewRequest(http.MethodPost, tc.url, bytes.NewReader(reqBytes))
33
	if err != nil {
34
		return "", errors.Wrap(err, "could not construct the request")
35
	}
36
	req.Header.Set("content-type", "application/json")
37
	resp, err := tc.client.Do(req)
38
	if err != nil {
39
		return "", errors.Wrap(err, "could not execute the request")
40
	}
41
	defer resp.Body.Close()
42
	body, err := io.ReadAll(resp.Body)
43
	if err != nil {
44
		return "", errors.Wrap(err, "could not read a body of the request")
45
	}
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 != "" {
50
				return "", &kumaErr
51
			}
52
		}
53
		return "", errors.Errorf("(%d): %s", resp.StatusCode, body)
54
	}
55
	return string(body), nil
56
}
57

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.