request/api.go

55 lines
1.4 KiB
Go
Raw Normal View History

2019-06-09 13:05:36 +00:00
package request
import (
2019-11-21 22:37:26 +00:00
"fmt"
"io"
"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 io.Reader) (*Response, error) {
req, err := http.NewRequest(method, url, data)
if err != nil {
return &Response{method, http.StatusInternalServerError, req.URL, nil, err}, err
}
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 io.Reader, 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
}