-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient_image.go
More file actions
75 lines (70 loc) · 2 KB
/
client_image.go
File metadata and controls
75 lines (70 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package mbz
import (
"context"
"fmt"
"io"
"log"
"net/http"
"github.com/way-platform/mbz-go/api/vehiclespecificationfleetv1"
)
// GetImageRequest is the request for [Client.GetImage].
type GetImageRequest struct {
// ImageID is the UUID of the image to download.
ImageID string `json:"imageId"`
}
// GetImageResponse is the response for [Client.GetImage].
type GetImageResponse struct {
// Data is the binary image data.
Data []byte
// ContentType is the MIME type of the image (e.g., "image/png", "image/jpeg", "image/webp").
ContentType string
}
// GetImage downloads the vehicle image for a given image ID.
// This method requires API key authentication via [WithAPIKey].
func (c *Client) GetImage(
ctx context.Context,
request *GetImageRequest,
opts ...ClientOption,
) (_ *GetImageResponse, err error) {
defer func() {
if err != nil {
err = fmt.Errorf("mbz: get image: %w", err)
}
}()
cfg := c.config.with(opts...)
if request.ImageID == "" {
return nil, fmt.Errorf("image ID is required")
}
requestURL := fmt.Sprintf("%s/images/%s", vehiclespecificationfleetv1.BaseURL, request.ImageID)
httpRequest, err := http.NewRequestWithContext(ctx, http.MethodGet, requestURL, nil)
if err != nil {
return nil, err
}
httpRequest.Header.Set("User-Agent", getUserAgent())
// Accept any image format
httpRequest.Header.Set("Accept", "image/png,image/jpeg,image/webp,*/*")
httpResponse, err := c.httpClient(cfg).Do(httpRequest)
if err != nil {
return nil, err
}
defer func() {
if closeErr := httpResponse.Body.Close(); closeErr != nil {
log.Printf("mbz: failed to close response body: %v", closeErr)
}
}()
if httpResponse.StatusCode != http.StatusOK {
return nil, newResponseError(httpResponse)
}
imageData, err := io.ReadAll(httpResponse.Body)
if err != nil {
return nil, err
}
contentType := httpResponse.Header.Get("Content-Type")
if contentType == "" {
contentType = "application/octet-stream"
}
return &GetImageResponse{
Data: imageData,
ContentType: contentType,
}, nil
}