summary refs log tree commit diff stats
path: root/pkg/cetus/req.go
blob: 84e52a5d829c454bb746739355891902506dda92 (plain) (blame)
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
package cetus

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"time"
)

// GetRes returns api response
func GetRes(api string, params map[string]string, t time.Duration) (string, error) {
	c := http.Client{
		Timeout: time.Second * t,
	}

	req, err := http.NewRequest(http.MethodGet, api, nil)
	if err != nil {
		return "", err
	}

	q := req.URL.Query()
	for k, v := range params {
		q.Add(k, v)
	}
	req.URL.RawQuery = q.Encode()

	res, err := c.Do(req)
	if err != nil {
		return "", err
	}
	defer res.Body.Close()

	if res.StatusCode != 200 {
		return "", fmt.Errorf("Unexpected response status code received: %d %s",
			res.StatusCode, http.StatusText(res.StatusCode))
	}

	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return "", err
	}
	return string(body), err
}