← history for tlsclient.go
6dfb9934tlsclient.go68 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
package main

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

func (c *RemoteChatApp) secureHttpClient(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 *RemoteChatApp) ApiPost(endpoint string, body string) string {
	var client *http.Client
	if c.config.Insecure == "true" {
		client = &http.Client{}
	} else {
		cert := path.Join(c.config.TlsCertificate)
		certKey := path.Join(c.config.TlsKeyFile)
		client = c.secureHttpClient(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)
	}

	var r ollamaResponse
	if err := json.NewDecoder(resp.Body).Decode(&r); err != nil {
		return ""
	}

	defer resp.Body.Close()
	return r.Response
}