-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
69 lines (58 loc) · 1.31 KB
/
client.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
package client
import (
"encoding/json"
"image"
"io"
"net"
"net/http"
"time"
)
// Client interface for interaction with the service
type Client interface {
DetectFaces(r io.Reader)
}
// FaceDetect is a http client for the face detection service
type FaceDetect struct {
httpClient *http.Client
location string
}
// Response is returned by a successful face detecion call
type Response struct {
Faces []image.Rectangle
Bounds image.Rectangle
}
// NewClient creates a new FaceDetect
func NewClient(l string) *FaceDetect {
hc := http.DefaultClient
hc.Timeout = 60 * time.Second
// force transport to use ipv4
hc.Transport = &http.Transport{
Dial: (func(network, addr string) (net.Conn, error) {
return (&net.Dialer{
Timeout: 3 * time.Second,
LocalAddr: nil,
DualStack: false,
}).Dial("tcp4", addr)
}),
}
return &FaceDetect{hc, l}
}
// DetectFaces sends a request to the face detection service
func (h *FaceDetect) DetectFaces(r io.Reader) (*Response, error) {
req, err := http.NewRequest("POST", h.location, r)
if err != nil {
return nil, err
}
resp, err := h.httpClient.Do(req)
if err != nil {
return nil, err
}
faces := &Response{}
defer resp.Body.Close()
d := json.NewDecoder(resp.Body)
err = d.Decode(faces)
if err != nil {
return nil, err
}
return faces, nil
}