/
loader.go
79 lines (69 loc) · 1.87 KB
/
loader.go
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
76
77
78
79
package main
import (
"io/ioutil"
"net/http"
"strings"
"time"
"github.com/ahamtat/micropic/internal/adapters/logger"
"github.com/ahamtat/micropic/internal/domain/entities"
)
// HTTPImageLoader structure
type HTTPImageLoader struct{}
// NewHTTPImageLoader constructor
func NewHTTPImageLoader() *HTTPImageLoader {
return &HTTPImageLoader{}
}
// Load image from HTTP source with request params
func (l *HTTPImageLoader) Load(request *entities.Request) ([]byte, *entities.Status) {
// Create HTTP request to image source
req, err := http.NewRequest("GET", "http://"+request.Params.URL, nil)
if err != nil {
errText := "error allocating http request"
logger.Error(errText, "error", err)
return nil, &entities.Status{
Code: http.StatusInternalServerError,
Text: errText,
}
}
// Proxying HTTP headers to request
for key, value := range request.Headers {
req.Header.Add(key, strings.Join(value, " "))
}
// Make request to image source
client := &http.Client{
Timeout: 5 * time.Second,
}
resp, err := client.Do(req)
if err != nil {
logger.Error("failed getting image from HTTP source",
"url", request.Params.URL, "error", err)
if resp == nil {
return nil, &entities.Status{
Code: http.StatusServiceUnavailable,
Text: http.StatusText(http.StatusServiceUnavailable),
}
}
return nil, &entities.Status{
Code: resp.StatusCode,
Text: http.StatusText(resp.StatusCode),
}
}
defer func() {
_ = resp.Body.Close()
}()
// Read image from response
image, err := ioutil.ReadAll(resp.Body)
if err != nil {
logger.Error("cannot read response body", "error", err)
return nil, &entities.Status{
Code: http.StatusNoContent,
Text: http.StatusText(http.StatusNoContent),
}
}
// TODO: Check for image format
// Image loaded successfully
return image, &entities.Status{
Code: resp.StatusCode,
Text: http.StatusText(resp.StatusCode),
}
}