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 defaultOpts Options serverURL string } func (c *Client) ServerURL() string { return c.serverURL } func (c *Client) apiGet(ctx context.Context, path string, result any, funcs ...OptionFunc) error { if err := c.apiDo(ctx, http.MethodGet, path, nil, result, funcs...); err != nil { return errors.WithStack(err) } return nil } func (c *Client) apiPost(ctx context.Context, path string, payload any, result any, funcs ...OptionFunc) error { if err := c.apiDo(ctx, http.MethodPost, path, payload, result, funcs...); err != nil { return errors.WithStack(err) } return nil } func (c *Client) apiPut(ctx context.Context, path string, payload any, result any, funcs ...OptionFunc) error { if err := c.apiDo(ctx, http.MethodPut, path, payload, result, funcs...); err != nil { return errors.WithStack(err) } return nil } func (c *Client) apiDelete(ctx context.Context, path string, payload any, result any, funcs ...OptionFunc) error { if err := c.apiDo(ctx, http.MethodDelete, path, payload, result, funcs...); err != nil { return errors.WithStack(err) } return nil } func (c *Client) apiDo(ctx context.Context, method string, path string, payload any, response any, funcs ...OptionFunc) error { opts := c.defaultOptions() for _, fn := range funcs { fn(opts) } 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) } for key, values := range opts.Headers { for _, v := range values { req.Header.Add(key, v) } } 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 (c *Client) defaultOptions() *Options { return &Options{ Headers: c.defaultOpts.Headers, } } 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, funcs ...OptionFunc) *Client { opts := Options{} for _, fn := range funcs { fn(&opts) } return &Client{ serverURL: serverURL, http: &http.Client{}, defaultOpts: opts, } }