summaryrefslogtreecommitdiff
path: root/internal/easyhttp/easyhttp.go
blob: ca10a8ecc77683084db17c4d9180856ea1992a0d (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
package easyhttp

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

func Get(uri, apiKey string) ([]byte, error) {
	var (
		client = &http.Client{}
		bytes []byte
	)

	req, err := http.NewRequest("GET", uri, nil)
	if err != nil {
		return bytes, fmt.Errorf("%s: %w", uri, err)
	} 

	req.Header.Set("X-API-KEY", apiKey)

	resp, err := client.Do(req)
	if err != nil {
		return bytes, fmt.Errorf("%s: %w", uri, err)
	}
	defer resp.Body.Close()

	bytes, err = io.ReadAll(resp.Body)
	if err != nil {
		return bytes, fmt.Errorf("%s: %w", uri, err)
	}

	return bytes, nil
}

// Get data from JSON
func GetData[T any](uri, apiKey string, data *T) error {
 	bytes, err := Get(uri, apiKey)
 	if err != nil {
 		return err
 	}

	return json.Unmarshal(bytes, data)
}

// Submiut structure as JSON to API
func SubmitData[T any](servers []string, uri, apiKey string, data *T) error {
	return nil
}