-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpicture.go
78 lines (59 loc) · 1.3 KB
/
picture.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
package main
import (
"strings"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
)
const baseURL = "https://api.cognitive.microsoft.com/bing/v7.0/images/search"
type Response struct {
Value []Image `json:"value"`
}
type Image struct {
ContentURL string `json"contentUrl"`
}
// GetPictureURL returns the url for the picture
func GetPictureURL(recipe Recipe) string {
apiKey := os.Getenv("BING_SEARCH_API_KEY")
url := fmt.Sprintf("%s?q=%s", baseURL, url.QueryEscape(recipe.Title))
resp, err := makeRequest(url, apiKey)
if err != nil {
panic(err)
}
json, err := parseJSON(resp)
for _, img := range json.Value {
if strings.HasPrefix(img.ContentURL, "https") {
return img.ContentURL
}
}
return ""
}
func parseJSON(body []byte) (*Response, error) {
var data = &Response{}
err := json.Unmarshal(body, &data)
if err != nil {
return nil, err
}
return data, nil
}
func makeRequest(url string, key string) ([]byte, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
req.Header.Set("Ocp-Apim-Subscription-Key", key)
var client = &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return body, nil
}