← history for client/apiclient.go
012f29ebclient/apiclient.go94 lines⬡ raw↓ download
 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
86
87
88
89
90
91
92
93
94
/**
 * 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 client

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

type YatsClient struct {
    Config ClientConfiguration
}

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 {
    certKey := path.Join(c.Config.ClientCertDir, c.Config.ClientCn+".key")
    cert := path.Join(c.Config.ClientCertDir, c.Config.ClientCn+".crt")

    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 {
    certKey := path.Join(c.Config.ClientCertDir, c.Config.ClientCn+".key")
    cert := path.Join(c.Config.ClientCertDir, c.Config.ClientCn+".crt")
    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)
}