request/api.go

57 lines
1.5 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"
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
}
2020-01-02 03:34:02 +00:00
// API sends RESTful API requests
func API(method, url string, headers map[string]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")
for k, v := range headers {
req.Header.Set(k, v)
}
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, headers map[string]string, data []byte, ch chan<- *Response, wg *sync.WaitGroup) {
defer wg.Done()
resp, _ := API(method, url, headers, data)
ch <- resp
2020-01-02 01:02:33 +00:00
}