emissary/internal/client/client.go

105 lines
1.8 KiB
Go
Raw Normal View History

2023-02-02 10:55:24 +01:00
package client
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/api"
"gitlab.com/wpetit/goweb/logger"
)
type Client struct {
http *http.Client
serverURL string
}
func (c *Client) apiGet(ctx context.Context, path string, result any) error {
if err := c.apiDo(ctx, http.MethodGet, path, nil, result); err != nil {
return errors.WithStack(err)
}
return nil
}
func (c *Client) apiPost(ctx context.Context, path string, payload any, result any) error {
if err := c.apiDo(ctx, http.MethodPost, path, payload, result); err != nil {
return errors.WithStack(err)
}
return nil
}
func (c *Client) apiDo(ctx context.Context, method string, path string, payload any, response any) error {
url := c.serverURL + path
logger.Debug(
ctx, "new http request",
logger.F("method", method),
logger.F("url", url),
logger.F("payload", payload),
)
var buf bytes.Buffer
encoder := json.NewEncoder(&buf)
if err := encoder.Encode(payload); err != nil {
return errors.WithStack(err)
}
req, err := http.NewRequest(method, url, &buf)
if err != nil {
return errors.WithStack(err)
}
res, err := c.http.Do(req)
if err != nil {
return errors.WithStack(err)
}
defer res.Body.Close()
decoder := json.NewDecoder(res.Body)
if err := decoder.Decode(&response); err != nil {
return errors.WithStack(err)
}
return nil
}
func withResponse[T any]() struct {
Data T
Error *api.Error
} {
return struct {
Data T
Error *api.Error
}{}
}
func joinSlice[T any](items []T) string {
str := ""
for idx, item := range items {
if idx != 0 {
str += ","
}
str += fmt.Sprintf("%v", item)
}
return str
}
func New(serverURL string) *Client {
return &Client{
serverURL: serverURL,
http: &http.Client{},
}
}