/** * Yats - yats * * This file is licensed under the Affero General Public License version 3 or * later. See the COPYING file. * * @author Paolo Lulli * @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) }