yats.git

ref: 3d473f4ebb4edaf7f7185d17ea54bdb0244bba7c

client/apiclient.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
/**
 * Yats - yats
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Paolo Lulli <kevwe.com>
 * @copyright Paolo Lulli 2024
 */
package main

import (
	"bytes"
	"crypto/tls"
	"fmt"
	"io"
	"net/http"
	"os"
)

func (c *YatsClient) httpClient(key string, cert string) (client *http.Client) {
	x509cert, err := tls.LoadX509KeyPair(cert, key)

	if err != nil {
		fmt.Printf("Error loading X509 certificate: %s and/or key: %s", cert, key)
		panic(err.Error())
	}
	certs := []tls.Certificate{x509cert}
	if len(certs) == 0 {
		client = &http.Client{}
		return
	}
	insecureSkipVerify := false
	if c.config.TlsVerifyServer == "false" {
		insecureSkipVerify = true
	}

	tr := &http.Transport{
		TLSClientConfig: &tls.Config{Certificates: certs,
			InsecureSkipVerify: insecureSkipVerify},
	}
	client = &http.Client{Transport: tr}
	return
}

func (c *YatsClient) ApiGet(endpoint string) string {
	cert, certKey := c.config.TlsCertificate, c.config.TlsKeyFile
	client := c.httpClient(certKey, cert)

	req, err := http.NewRequest("GET", endpoint, nil)
	if err != nil {
		fmt.Println("Unable to make GET request", err)
		os.Exit(1)
	}
	req.Header.Add("Accept", "*/*")
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	defer resp.Body.Close()
	data, _ := io.ReadAll(resp.Body)
	return string(data)
}

func (c *YatsClient) ApiPost(endpoint string, body string) string {
	cert, certKey := c.config.TlsCertificate, c.config.TlsKeyFile
	client := c.httpClient(certKey, cert)

	req, err := http.NewRequest("POST", endpoint, bytes.NewBuffer([]byte(body)))
	req.Header.Set("Content-Type", "application/json; charset=UTF-8")
	if err != nil {
		fmt.Println("Unable to make POST request", err)
		os.Exit(1)
	}
	req.Header.Add("Accept", "*/*")
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	defer resp.Body.Close()
	data, _ := io.ReadAll(resp.Body)
	return string(data)
}