package imaginary import ( "bytes" "fmt" "io" "mime/multipart" "net/http" ) type Client struct { baseURL string http *http.Client } func New(baseURL string) *Client { return &Client{ baseURL: baseURL, http: &http.Client{}, } } type ProcessOptions struct { Width int Height int Quality int Type string } func (c *Client) Process(src io.Reader, filename string, opts ProcessOptions) ([]byte, error) { var body bytes.Buffer writer := multipart.NewWriter(&body) part, err := writer.CreateFormFile("file", filename) if err != nil { return nil, err } if _, err := io.Copy(part, src); err != nil { return nil, err } writer.Close() if opts.Width == 0 { opts.Width = 2000 } if opts.Height == 0 { opts.Height = 2000 } if opts.Quality == 0 { opts.Quality = 80 } if opts.Type == "" { opts.Type = "webp" } url := fmt.Sprintf("%s/resize?width=%d&height=%d&quality=%d&type=%s", c.baseURL, opts.Width, opts.Height, opts.Quality, opts.Type) req, err := http.NewRequest("POST", url, &body) if err != nil { return nil, err } req.Header.Set("Content-Type", writer.FormDataContentType()) resp, err := c.http.Do(req) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { errBody, _ := io.ReadAll(resp.Body) return nil, fmt.Errorf("imaginary error %d: %s", resp.StatusCode, string(errBody)) } return io.ReadAll(resp.Body) }