2019-10-05 21:53:22 +05:00
|
|
|
package requester
|
|
|
|
|
|
|
|
import (
|
|
|
|
// stdlib
|
2019-10-07 18:21:26 +05:00
|
|
|
"bytes"
|
|
|
|
"encoding/json"
|
2019-10-05 21:53:22 +05:00
|
|
|
"io/ioutil"
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
// local
|
2019-10-13 15:12:54 +05:00
|
|
|
"go.dev.pztrn.name/giredore/internal/logger"
|
2019-10-05 21:53:22 +05:00
|
|
|
|
|
|
|
// other
|
|
|
|
"github.com/rs/zerolog"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
log zerolog.Logger
|
|
|
|
)
|
|
|
|
|
|
|
|
func Initialize() {
|
|
|
|
log = logger.Logger.With().Str("type", "internal").Str("package", "requester").Logger()
|
|
|
|
log.Info().Msg("Initializing...")
|
|
|
|
}
|
|
|
|
|
2019-10-07 18:21:26 +05:00
|
|
|
func Delete(url string, data interface{}) ([]byte, error) {
|
|
|
|
return execRequest("DELETE", url, data)
|
|
|
|
}
|
|
|
|
|
|
|
|
func execRequest(method string, url string, data interface{}) ([]byte, error) {
|
2019-10-05 21:53:22 +05:00
|
|
|
log.Debug().Str("method", method).Str("URL", url).Msg("Trying to execute HTTP request...")
|
|
|
|
|
|
|
|
httpClient := getHTTPClient()
|
|
|
|
|
2019-10-07 18:21:26 +05:00
|
|
|
var dataToSend []byte
|
|
|
|
if data != nil {
|
|
|
|
dataToSend, _ = json.Marshal(data)
|
|
|
|
}
|
|
|
|
|
2019-10-05 21:53:22 +05:00
|
|
|
// Compose HTTP request.
|
2019-10-07 18:21:26 +05:00
|
|
|
httpReq, err := http.NewRequest(method, url, bytes.NewReader(dataToSend))
|
2019-10-05 21:53:22 +05:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
response, err1 := httpClient.Do(httpReq)
|
|
|
|
if err1 != nil {
|
|
|
|
return nil, err1
|
|
|
|
}
|
|
|
|
|
|
|
|
bodyBytes, err2 := ioutil.ReadAll(response.Body)
|
|
|
|
if err2 != nil {
|
|
|
|
return nil, err2
|
|
|
|
}
|
|
|
|
response.Body.Close()
|
|
|
|
|
|
|
|
log.Debug().Int("response body length (bytes)", len(bodyBytes)).Msg("Got response")
|
|
|
|
|
|
|
|
return bodyBytes, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func Get(url string) ([]byte, error) {
|
|
|
|
return execRequest("GET", url, nil)
|
|
|
|
}
|
2019-10-07 18:21:26 +05:00
|
|
|
|
|
|
|
func Post(url string, data interface{}) ([]byte, error) {
|
|
|
|
return execRequest("POST", url, data)
|
|
|
|
}
|
|
|
|
|
|
|
|
func Put(url string, data interface{}) ([]byte, error) {
|
|
|
|
return execRequest("PUT", url, data)
|
|
|
|
}
|