summaryrefslogtreecommitdiff
path: root/pkg/gitlab/client.go
blob: a43e09e6fca4f279e7eafd43f3702288a56e2d00 (plain)
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
package gitlab

import (
	"bytes"
	"context"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"

	"github.com/xlgmokha/x/pkg/env"
	"github.com/xlgmokha/x/pkg/x"
)

type GitLab struct {
	ctx    context.Context
	client http.Client
	token  string
	url    string
}

func New(ctx context.Context, token string) *GitLab {
	return &GitLab{
		ctx:    ctx,
		client: http.Client{},
		token:  token,
		url:    "https://gitlab.com/api/v4",
	}
}

func (gl *GitLab) Group(id int) *Group {
	return NewGroup(gl, id)
}

func (gl *GitLab) Get(url string) *http.Response {
	return gl.execute(gl.newRequest("GET", url))
}

func (gl *GitLab) newRequest(method string, url string) *http.Request {
	request := x.Must(http.NewRequestWithContext(gl.ctx, "GET", url, nil))
	request.Header.Add("Authorization", fmt.Sprintf("Bearer %v", gl.token))
	return request
}

func (gl *GitLab) execute(request *http.Request) *http.Response {
	response := x.Must(gl.client.Do(request))

	if env.Fetch("DUMP", "") != "" {
		body := x.Must(io.ReadAll(response.Body))
		fmt.Println(string(body))
		response.Body = ioutil.NopCloser(bytes.NewBuffer(body))
	}
	return response
}