agecem-org/api/api.go

101 lines
1.8 KiB
Go

package api
import (
"errors"
"fmt"
"io/ioutil"
"net/http"
)
type API struct {
Protocol string
Host string
Port int
Opts APIOptions
}
type APIOptions struct {
KeyAuth bool
Key string
}
func New(protocol, host string, port int, opts APIOptions) (*API, error) {
api := API{
Protocol: protocol,
Host: host,
Port: port,
Opts: opts,
}
return &api, nil
}
// Call returns a []byte representing a response body.
// Can be used for GET or DELETE methods
func (a *API) Call(method, route string) ([]byte, error) {
endpoint := fmt.Sprintf("%s://%s:%d",
a.Protocol,
a.Host,
a.Port,
)
request := fmt.Sprintf("%s%s", endpoint, route)
switch method {
case http.MethodGet:
// Create client
client := &http.Client{}
// Create request
request, err := http.NewRequest(http.MethodGet, request, nil)
if err != nil {
return nil, err
}
if a.Opts.KeyAuth {
request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", a.Opts.Key))
}
// Fetch Request
response, err := client.Do(request)
if err != nil {
return nil, err
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
return body, nil
case http.MethodDelete:
// Create client
client := &http.Client{}
// Create request
req, err := http.NewRequest(http.MethodDelete, request, nil)
if err != nil {
return nil, err
}
if a.Opts.KeyAuth {
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", a.Opts.Key))
}
// Fetch Request
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// Read Response Body
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return respBody, nil
}
return nil, errors.New(fmt.Sprintf("method must be 'GET' or 'DELETE', got '%s'", method))
}