76 lines
1.7 KiB
Go
76 lines
1.7 KiB
Go
|
package apis
|
||
|
|
||
|
import (
|
||
|
"encoding/json"
|
||
|
"errors"
|
||
|
"fmt"
|
||
|
"io"
|
||
|
"io/ioutil"
|
||
|
"net/http"
|
||
|
"reflect"
|
||
|
|
||
|
"github.com/sirupsen/logrus"
|
||
|
)
|
||
|
|
||
|
// Errors
|
||
|
var (
|
||
|
ErrAPICall = errors.New("API call fail")
|
||
|
)
|
||
|
|
||
|
// GenRequest -
|
||
|
func GenRequest(targetURL, method, bearerToken string, headers map[string]string, body io.Reader) (*http.Request, error) {
|
||
|
logrus.Infof("[APIS][GenRequest] Generate Request from url : %s\n", targetURL)
|
||
|
req, err := http.NewRequest(method, targetURL, body)
|
||
|
if err != nil {
|
||
|
logrus.Errorf("[APIS][GenRequest] Create request fail : %s\n", err.Error())
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
if len(headers) > 0 {
|
||
|
for k, v := range headers {
|
||
|
req.Header.Set(k, v)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
if len(bearerToken) > 0 {
|
||
|
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", bearerToken))
|
||
|
}
|
||
|
|
||
|
return req, nil
|
||
|
}
|
||
|
|
||
|
// SendRequest -
|
||
|
func SendRequest(req *http.Request, data interface{}) (status int, b []byte, err error) {
|
||
|
logrus.Infof("[APIS][SendRequest] Send Request\n")
|
||
|
if req == nil {
|
||
|
logrus.Errorf("[APIS][SendRequest] Request Object Empty\n")
|
||
|
return 0, nil, errors.New("request object is empty")
|
||
|
}
|
||
|
|
||
|
resp, err := http.DefaultClient.Do(req)
|
||
|
if err != nil {
|
||
|
logrus.Errorf("[APIS][SendRequest] HTTP Request fail : %s\n", err.Error())
|
||
|
return -1, nil, err
|
||
|
}
|
||
|
defer resp.Body.Close()
|
||
|
|
||
|
b, err = ioutil.ReadAll(resp.Body)
|
||
|
if err != nil {
|
||
|
logrus.Errorf("[APIS][SendRequest] Read RespBody fail : %s\n", err.Error())
|
||
|
return resp.StatusCode, b, err
|
||
|
}
|
||
|
if data != nil {
|
||
|
t := reflect.TypeOf(data)
|
||
|
if t.Kind() == reflect.Ptr {
|
||
|
|
||
|
err = json.Unmarshal(b, data)
|
||
|
if err != nil {
|
||
|
logrus.Errorf("[APIS][SendRequest] JSON parse fail : %s\n", err.Error())
|
||
|
return resp.StatusCode, b, err
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return resp.StatusCode, b, nil
|
||
|
}
|