|
| 1 | +package facebox |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "encoding/json" |
| 6 | + "io" |
| 7 | + "mime/multipart" |
| 8 | + "net/url" |
| 9 | + |
| 10 | + "github.com/pkg/errors" |
| 11 | +) |
| 12 | + |
| 13 | +// Check checks the image in the io.Reader for faces. |
| 14 | +func (c *Client) Check(image io.Reader) ([]Face, error) { |
| 15 | + var buf bytes.Buffer |
| 16 | + w := multipart.NewWriter(&buf) |
| 17 | + fw, err := w.CreateFormFile("file", "image.dat") |
| 18 | + if err != nil { |
| 19 | + return nil, err |
| 20 | + } |
| 21 | + _, err = io.Copy(fw, image) |
| 22 | + if err != nil { |
| 23 | + return nil, err |
| 24 | + } |
| 25 | + if err = w.Close(); err != nil { |
| 26 | + return nil, err |
| 27 | + } |
| 28 | + u, err := url.Parse(c.addr + "/facebox/check") |
| 29 | + if err != nil { |
| 30 | + return nil, err |
| 31 | + } |
| 32 | + if !u.IsAbs() { |
| 33 | + return nil, errors.New("box address must be absolute") |
| 34 | + } |
| 35 | + resp, err := c.HTTPClient.Post(u.String(), w.FormDataContentType(), &buf) |
| 36 | + if err != nil { |
| 37 | + return nil, err |
| 38 | + } |
| 39 | + defer resp.Body.Close() |
| 40 | + return c.parseCheckResponse(resp.Body) |
| 41 | +} |
| 42 | + |
| 43 | +// CheckURL checks the image at the specified URL for faces. |
| 44 | +func (c *Client) CheckURL(imageURL *url.URL) ([]Face, error) { |
| 45 | + u, err := url.Parse(c.addr + "/facebox/check") |
| 46 | + if err != nil { |
| 47 | + return nil, err |
| 48 | + } |
| 49 | + if !u.IsAbs() { |
| 50 | + return nil, errors.New("box address must be absolute") |
| 51 | + } |
| 52 | + if !imageURL.IsAbs() { |
| 53 | + return nil, errors.New("url must be absolute") |
| 54 | + } |
| 55 | + form := url.Values{} |
| 56 | + form.Set("url", imageURL.String()) |
| 57 | + resp, err := c.HTTPClient.PostForm(u.String(), form) |
| 58 | + if err != nil { |
| 59 | + return nil, err |
| 60 | + } |
| 61 | + defer resp.Body.Close() |
| 62 | + return c.parseCheckResponse(resp.Body) |
| 63 | +} |
| 64 | + |
| 65 | +func (c *Client) parseCheckResponse(r io.Reader) ([]Face, error) { |
| 66 | + var checkResponse struct { |
| 67 | + Success bool |
| 68 | + Error string |
| 69 | + Faces []Face |
| 70 | + } |
| 71 | + if err := json.NewDecoder(r).Decode(&checkResponse); err != nil { |
| 72 | + return nil, errors.Wrap(err, "decoding response") |
| 73 | + } |
| 74 | + if !checkResponse.Success { |
| 75 | + return nil, ErrFacebox(checkResponse.Error) |
| 76 | + } |
| 77 | + return checkResponse.Faces, nil |
| 78 | +} |
0 commit comments