init
This commit is contained in:
commit
d69342b2e9
160 changed files with 28681 additions and 0 deletions
77
internal/imaginary/client.go
Normal file
77
internal/imaginary/client.go
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
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)
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue