2019-10-05 21:53:22 +05:00
|
|
|
package requester
|
|
|
|
|
|
|
|
import (
|
2019-10-07 18:21:26 +05:00
|
|
|
"bytes"
|
2021-11-20 23:06:40 +05:00
|
|
|
"context"
|
2019-10-07 18:21:26 +05:00
|
|
|
"encoding/json"
|
2019-10-05 21:53:22 +05:00
|
|
|
"io/ioutil"
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/rs/zerolog"
|
2021-11-20 23:06:40 +05:00
|
|
|
"go.dev.pztrn.name/giredore/internal/logger"
|
2019-10-05 21:53:22 +05:00
|
|
|
)
|
|
|
|
|
2021-11-20 23:06:40 +05:00
|
|
|
var log zerolog.Logger
|
2019-10-05 21:53:22 +05:00
|
|
|
|
|
|
|
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)
|
|
|
|
}
|
|
|
|
|
2021-11-20 23:06:40 +05:00
|
|
|
// nolint:wrapcheck
|
2019-10-07 18:21:26 +05:00
|
|
|
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.
|
2021-11-20 23:06:40 +05:00
|
|
|
httpReq, err := http.NewRequestWithContext(context.Background(), 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
|
|
|
|
}
|
2019-10-16 23:32:21 +05:00
|
|
|
|
2019-10-05 21:53:22 +05:00
|
|
|
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)
|
|
|
|
}
|