oc-lib/tools/remote_caller.go
2024-08-13 09:49:42 +02:00

59 lines
1.1 KiB
Go

package tools
import (
"bytes"
"encoding/json"
"io"
"net/http"
)
type METHOD int
const (
GET METHOD = iota
PUT
POST
DELETE
)
var HTTPCallerInstance = &HTTPCaller{}
type HTTPCaller struct {
URLS map[string]map[METHOD]string
}
func NewHTTPCaller(urls map[string]map[METHOD]string) *HTTPCaller {
return &HTTPCaller{
URLS: urls,
}
}
func (caller *HTTPCaller) CallGet(url string, subpath string) ([]byte, error) {
resp, err := http.Get(url + subpath)
if err != nil {
return nil, err
}
defer resp.Body.Close()
return io.ReadAll(resp.Body)
}
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)
}
func (caller *HTTPCaller) CallPost(url string, subpath string, body map[string]interface{}) ([]byte, error) {
postBody, _ := json.Marshal(body)
responseBody := bytes.NewBuffer(postBody)
resp, err := http.Post(url+subpath, "application/json", responseBody)
if err != nil {
return nil, err
}
defer resp.Body.Close()
return io.ReadAll(resp.Body)
}