-
Notifications
You must be signed in to change notification settings - Fork 1
/
image-service.go
71 lines (58 loc) · 1.39 KB
/
image-service.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
package main
import (
_"fmt"
"strings"
"io"
"io/ioutil"
"net/http"
_"net/url"
"os"
)
type queryParams struct {
query string
}
func health(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "I am alive!")
}
func (s queryParams) createSeachURL() string {
searchURL := []string{"https://www.googleapis.com/customsearch/v1?"}
query := make(map[string]string)
query["q"] = s.query
query["searchType"] = "image"
query["fields"] = "items(link)"
// add your google api keys
query["cx"] = ""
query["key"] = ""
// override defaults
if os.Getenv("GOOGLE_CX") != "" {
query["cx"] = os.Getenv("GOOGLE_CX")
}
if os.Getenv("GOOGLE_KEY") != "" {
query["key"] = os.Getenv("GOOGLE_KEY")
}
for k, v := range query {
searchURL = append(searchURL, k,"=",v,"&")
}
return strings.Join(searchURL, "")
}
func image (w http.ResponseWriter, r *http.Request) {
//image?search=XXXX
query := queryParams{r.URL.Query().Get("search")}
imageSearch := query.createSeachURL()
request, err := http.Get(imageSearch)
if err != nil {
panic(err)
}
if request.StatusCode != http.StatusOK {
panic("http status code not 200")
}
defer request.Body.Close()
content, _ := ioutil.ReadAll(request.Body)
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(content))
}
func main() {
http.HandleFunc("/", health)
http.HandleFunc("/image", image)
http.ListenAndServe(":8888", nil)
}