request/api.go

65 lines
1.5 KiB
Go
Raw Normal View History

2019-06-09 13:05:36 +00:00
package request
import (
"encoding/json"
2019-11-21 22:37:26 +00:00
"errors"
"fmt"
"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
// 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-11-11 00:46:47 +00:00
return nil, &HTTPError{StatusCode: http.StatusInternalServerError, Error: 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-11-11 00:46:47 +00:00
return nil, &HTTPError{StatusCode: http.StatusInternalServerError, Error: err}
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
2019-11-11 00:46:47 +00:00
return nil, &HTTPError{StatusCode: http.StatusInternalServerError, Error: err}
}
defer resp.Body.Close()
if resp.StatusCode == 200 {
2019-06-20 00:33:48 +00:00
return body, nil
}
2019-11-21 22:37:26 +00:00
e := fmt.Sprintf("api: %s/%s - %d %s", r.URL, path, resp.StatusCode, http.StatusText(resp.StatusCode))
return nil, &HTTPError{StatusCode: resp.StatusCode, Error: errors.New(e)}
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-11-21 22:37:26 +00:00
fmt.Println(err.Error)
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
}