summaryrefslogtreecommitdiff
path: root/internal/gitlabnet/client.go
blob: 30ef4cc4b6cd65806a9f2a6e432140ed70cbf268 (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
package gitlabnet

import (
	"encoding/json"
	"fmt"
	"net"
	"net/http"

	"gitlab.com/gitlab-org/gitlab-shell/v14/client"

	"gitlab.com/gitlab-org/gitlab-shell/v14/internal/config"
)

var (
	ParsingError = fmt.Errorf("Parsing failed")
)

func GetClient(config *config.Config) (*client.GitlabNetClient, error) {
	httpClient, err := config.HttpClient()
	if err != nil {
		return nil, err
	}

	if httpClient == nil {
		return nil, fmt.Errorf("Unsupported protocol")
	}

	return client.NewGitlabNetClient(config.HttpSettings.User, config.HttpSettings.Password, config.Secret, httpClient)
}

func ParseJSON(hr *http.Response, response interface{}) error {
	if err := json.NewDecoder(hr.Body).Decode(response); err != nil {
		return ParsingError
	}

	return nil
}

func ParseIP(remoteAddr string) string {
	// The remoteAddr field can be filled by:
	// 1. An IP address via the SSH_CONNECTION environment variable
	// 2. A host:port combination via the PROXY protocol
	ip, _, err := net.SplitHostPort(remoteAddr)

	// If we don't have a port or can't parse this address for some reason,
	// just return the original string.
	if err != nil {
		return remoteAddr
	}

	return ip
}