Files
mtusi2026lab2/tools/concurrency/client.go
T

68 lines
1.6 KiB
Go

package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"time"
)
// client is a minimal typed HTTP client for the messenger API.
type client struct {
base string
http *http.Client
}
func newClient(baseURL string) *client {
return &client{base: baseURL, http: &http.Client{Timeout: 10 * time.Second}}
}
func (c *client) post(path, actor string, body, out any) error {
raw, err := json.Marshal(body)
if err != nil {
return err
}
req, err := http.NewRequest(http.MethodPost, c.base+path, bytes.NewReader(raw))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
return c.do(req, actor, http.StatusCreated, out)
}
// get requests the largest page the contract allows, continuing from cursor
// when it is set.
func (c *client) get(path, actor, cursor string, out any) error {
query := url.Values{"limit": {"100"}}
if cursor != "" {
query.Set("cursor", cursor)
}
req, err := http.NewRequest(http.MethodGet, c.base+path+"?"+query.Encode(), nil)
if err != nil {
return err
}
return c.do(req, actor, http.StatusOK, out)
}
func (c *client) do(req *http.Request, actor string, want int, out any) error {
if actor != "" {
req.Header.Set("X-User-Id", actor)
}
resp, err := c.http.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
payload, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
if err != nil {
return err
}
if resp.StatusCode != want {
return fmt.Errorf("%s %s: status %d, want %d: %s", req.Method, req.URL.Path, resp.StatusCode, want, payload)
}
return json.Unmarshal(payload, out)
}