2019-06-09 13:05:36 +00:00
|
|
|
package request
|
|
|
|
|
|
|
|
import (
|
2020-01-02 01:02:33 +00:00
|
|
|
"bytes"
|
2019-11-21 22:37:26 +00:00
|
|
|
"fmt"
|
2019-06-13 17:11:42 +00:00
|
|
|
"io/ioutil"
|
|
|
|
"net/http"
|
2020-01-02 01:02:33 +00:00
|
|
|
"net/url"
|
2020-05-13 13:35:30 +00:00
|
|
|
"sync"
|
2019-06-13 17:11:42 +00:00
|
|
|
"time"
|
2019-06-09 13:05:36 +00:00
|
|
|
)
|
|
|
|
|
2020-02-15 03:05:26 +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
|
2020-05-13 13:35:30 +00:00
|
|
|
Error error
|
2020-01-02 01:02:33 +00:00
|
|
|
}
|
|
|
|
|
2020-01-02 03:34:02 +00:00
|
|
|
// API sends RESTful API requests
|
2020-06-27 18:58:57 +00:00
|
|
|
func API(method, url string, headers map[string]string, data []byte) (*Response, error) {
|
2020-06-11 02:40:53 +00:00
|
|
|
req, err := http.NewRequest(method, url, bytes.NewBuffer(data))
|
2019-06-09 18:05:18 +00:00
|
|
|
if err != nil {
|
2020-06-27 18:58:57 +00:00
|
|
|
return &Response{method, http.StatusInternalServerError, req.URL, nil, err}, err
|
2019-06-13 17:11:42 +00:00
|
|
|
}
|
2020-06-11 02:40:53 +00:00
|
|
|
req.Header.Set("Accept", "application/json")
|
|
|
|
req.Header.Set("Content-Type", "application/json")
|
2020-06-27 18:58:57 +00:00
|
|
|
for k, v := range headers {
|
|
|
|
req.Header.Set(k, v)
|
|
|
|
}
|
2019-06-13 17:11:42 +00:00
|
|
|
client := &http.Client{Timeout: time.Second * 10}
|
|
|
|
resp, err := client.Do(req)
|
|
|
|
if err != nil {
|
2020-06-27 18:58:57 +00:00
|
|
|
return &Response{method, http.StatusInternalServerError, req.URL, nil, err}, err
|
2019-06-13 17:11:42 +00:00
|
|
|
}
|
|
|
|
body, err := ioutil.ReadAll(resp.Body)
|
|
|
|
if err != nil {
|
2020-06-27 18:58:57 +00:00
|
|
|
return &Response{method, http.StatusInternalServerError, req.URL, nil, err}, err
|
2019-06-13 17:11:42 +00:00
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
2019-06-09 18:05:18 +00:00
|
|
|
|
2019-06-13 17:11:42 +00:00
|
|
|
if resp.StatusCode == 200 {
|
2020-06-27 18:58:57 +00:00
|
|
|
return &Response{method, resp.StatusCode, resp.Request.URL, body, err}, nil
|
2019-06-13 17:11:42 +00:00
|
|
|
}
|
2020-06-11 02:40:53 +00:00
|
|
|
err = fmt.Errorf("api: %s - %d %s", url, resp.StatusCode, http.StatusText(resp.StatusCode))
|
2020-06-27 18:58:57 +00:00
|
|
|
return &Response{method, resp.StatusCode, resp.Request.URL, nil, err}, err
|
2020-02-10 18:52:36 +00:00
|
|
|
}
|
|
|
|
|
2020-02-13 21:50:00 +00:00
|
|
|
// AsyncAPI send requests concurrently
|
2020-06-27 18:58:57 +00:00
|
|
|
func AsyncAPI(method, url string, headers map[string]string, data []byte, ch chan<- *Response, wg *sync.WaitGroup) {
|
2020-05-13 13:35:30 +00:00
|
|
|
defer wg.Done()
|
2020-06-27 18:58:57 +00:00
|
|
|
resp, _ := API(method, url, headers, data)
|
2020-05-13 13:35:30 +00:00
|
|
|
ch <- resp
|
2020-01-02 01:02:33 +00:00
|
|
|
}
|