request/api.go

70 lines
1.4 KiB
Go
Raw Normal View History

2019-06-09 13:05:36 +00:00
package request
import (
"encoding/json"
"io/ioutil"
"net/http"
"strings"
"time"
2019-06-09 13:05:36 +00:00
)
2019-10-20 02:00:41 +00:00
// Request data
type Request struct {
URL string
Headers []string
}
// HTTPError Status
type HTTPError struct {
StatusCode int
Error error
2019-06-09 13:05:36 +00:00
}
2019-10-20 02:00:41 +00:00
// HTTPErr HTTP Error
func HTTPErr(StatusCode int, err error) *HTTPError {
return &HTTPError{
StatusCode: StatusCode,
Error: err}
}
// Get sends GET request to path
func Get(r *Request, path string) ([]byte, *HTTPError) {
req, err := http.NewRequest("GET", r.URL+"/"+path, nil)
if err != nil {
2019-10-20 02:00:41 +00:00
return nil, HTTPErr(http.StatusInternalServerError, err)
}
2019-10-20 02:00:41 +00:00
for i := 0; i < len(r.Headers); i++ {
header := strings.Split(r.Headers[i], ",")
req.Header.Set(header[0], header[1])
}
client := &http.Client{Timeout: time.Second * 10}
resp, err := client.Do(req)
if err != nil {
2019-10-20 02:00:41 +00:00
return nil, HTTPErr(http.StatusInternalServerError, err)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
2019-10-20 02:00:41 +00:00
return nil, HTTPErr(http.StatusInternalServerError, err)
}
defer resp.Body.Close()
if resp.StatusCode == 200 {
2019-06-20 00:33:48 +00:00
return body, nil
}
2019-10-20 02:00:41 +00:00
return nil, HTTPErr(resp.StatusCode, nil)
2019-06-09 13:05:36 +00:00
}
2019-10-20 02:00:41 +00:00
// JSONParse parses json data
func JSONParse(r *Request, path string) (map[string]interface{}, *HTTPError) {
var result map[string]interface{}
resp, err := Get(r, path)
2019-06-20 00:33:48 +00:00
if err != nil {
2019-10-20 02:00:41 +00:00
return nil, err
2019-06-20 00:33:48 +00:00
}
2019-10-20 02:00:41 +00:00
json.Unmarshal(resp, &result)
2019-06-18 01:48:55 +00:00
2019-10-20 02:00:41 +00:00
return result, nil
}