2024-08-12 16:11:25 +02:00
|
|
|
package tools
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"encoding/json"
|
|
|
|
"io"
|
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
2024-08-13 09:49:42 +02:00
|
|
|
type METHOD int
|
|
|
|
|
|
|
|
const (
|
|
|
|
GET METHOD = iota
|
|
|
|
PUT
|
|
|
|
POST
|
|
|
|
DELETE
|
|
|
|
)
|
|
|
|
|
2024-08-12 16:11:25 +02:00
|
|
|
var HTTPCallerInstance = &HTTPCaller{}
|
|
|
|
|
|
|
|
type HTTPCaller struct {
|
2024-08-13 09:49:42 +02:00
|
|
|
URLS map[string]map[METHOD]string
|
2024-08-12 16:11:25 +02:00
|
|
|
}
|
|
|
|
|
2024-08-13 09:49:42 +02:00
|
|
|
func NewHTTPCaller(urls map[string]map[METHOD]string) *HTTPCaller {
|
2024-08-12 16:11:25 +02:00
|
|
|
return &HTTPCaller{
|
2024-08-13 09:49:42 +02:00
|
|
|
URLS: urls,
|
2024-08-12 16:11:25 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (caller *HTTPCaller) CallGet(url string, subpath string) ([]byte, error) {
|
2024-08-12 16:21:38 +02:00
|
|
|
resp, err := http.Get(url + subpath)
|
2024-08-12 16:11:25 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
return io.ReadAll(resp.Body)
|
|
|
|
}
|
|
|
|
|
2024-08-13 09:49:42 +02:00
|
|
|
func (caller *HTTPCaller) CallDelete(url string, subpath string) ([]byte, error) {
|
|
|
|
resp, err := http.NewRequest("DELETE", url+subpath, nil)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
return io.ReadAll(resp.Body)
|
|
|
|
}
|
|
|
|
|
2024-08-21 16:03:56 +02:00
|
|
|
func (caller *HTTPCaller) CallPost(url string, subpath string, body interface{}) ([]byte, error) {
|
2024-08-12 16:11:25 +02:00
|
|
|
postBody, _ := json.Marshal(body)
|
|
|
|
responseBody := bytes.NewBuffer(postBody)
|
2024-08-12 16:21:38 +02:00
|
|
|
resp, err := http.Post(url+subpath, "application/json", responseBody)
|
2024-08-12 16:11:25 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
return io.ReadAll(resp.Body)
|
|
|
|
}
|