request/api.go

82 lines
2.1 KiB
Go
Raw Normal View History

2019-06-09 13:05:36 +00:00
package request
import (
2020-01-02 01:02:33 +00:00
"bytes"
"encoding/json"
2019-11-21 22:37:26 +00:00
"fmt"
"io/ioutil"
"net/http"
2020-01-02 01:02:33 +00:00
"net/url"
"sync"
"time"
2019-06-09 13:05:36 +00:00
)
// Response API return request
type Response struct {
2020-01-02 01:02:33 +00:00
Method string
StatusCode int
URL *url.URL
Body []byte
Error error
2020-01-02 01:02:33 +00:00
}
func response(method string, statuscode int, url *url.URL, body []byte, err error) *Response {
return &Response{
2020-01-02 01:02:33 +00:00
Method: method,
StatusCode: statuscode,
URL: url,
Body: body,
Error: err,
2020-01-02 01:02:33 +00:00
}
2019-06-09 13:05:36 +00:00
}
2020-01-02 03:34:02 +00:00
// API sends RESTful API requests
func API(method, url string, data []byte) (*Response, error) {
req, err := http.NewRequest(method, url, bytes.NewBuffer(data))
if err != nil {
return response(method, http.StatusInternalServerError, req.URL, nil, err), err
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
client := &http.Client{Timeout: time.Second * 10}
resp, err := client.Do(req)
if err != nil {
return response(method, http.StatusInternalServerError, req.URL, nil, err), err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return response(method, http.StatusInternalServerError, req.URL, nil, err), err
}
defer resp.Body.Close()
if resp.StatusCode == 200 {
return response(method, resp.StatusCode, resp.Request.URL, body, err), nil
}
err = fmt.Errorf("api: %s - %d %s", url, resp.StatusCode, http.StatusText(resp.StatusCode))
return response(method, resp.StatusCode, resp.Request.URL, nil, err), err
}
// AsyncAPI send requests concurrently
func AsyncAPI(method, url string, data []byte, ch chan<- *Response, wg *sync.WaitGroup) {
defer wg.Done()
resp, _ := API(method, url, data)
ch <- resp
2020-01-02 01:02:33 +00:00
}
// JSONResp Response
type JSONResp struct {
2020-01-02 01:02:33 +00:00
StatusCode int
Body map[string]interface{}
2019-06-09 13:05:36 +00:00
}
2019-10-20 02:00:41 +00:00
// JSONParse parses json data
func JSONParse(url string) (*JSONResp, error) {
2019-10-20 02:00:41 +00:00
var result map[string]interface{}
resp, err := API(http.MethodGet, url, nil)
2019-06-20 00:33:48 +00:00
if err != nil {
return &JSONResp{StatusCode: resp.StatusCode}, err
2019-06-20 00:33:48 +00:00
}
2020-01-02 01:02:33 +00:00
json.Unmarshal(resp.Body, &result)
return &JSONResp{StatusCode: resp.StatusCode, Body: result}, nil
}