/
http.go
45 lines (40 loc) · 942 Bytes
/
http.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
package main
import (
"encoding/json"
"fmt"
"net/http"
"google.golang.org/appengine"
"google.golang.org/appengine/urlfetch"
)
func init() {
http.HandleFunc("/", handleGetGif)
}
func handleGetGif(res http.ResponseWriter, req *http.Request) {
ctx := appengine.NewContext(req)
client := urlfetch.Client(ctx)
result, err := client.Get("http://api.giphy.com/v1/gifs/search?q=funny+cat&api_key=dc6zaTOxFJmzC")
if err != nil {
http.Error(res, err.Error(), 500)
return
}
defer result.Body.Close()
var obj struct {
Data []struct {
URL string `json:"url"`
Images struct {
Original struct {
URL string
}
}
}
}
err = json.NewDecoder(result.Body).Decode(&obj)
if err != nil {
http.Error(res, err.Error(), 500)
return
}
for _, img := range obj.Data {
fmt.Fprintf(res, `<a href="%v">%v</a><img src="%v"><br>`, img.URL, img.URL, img.Images.Original.URL)
}
}
// https://github.com/Giphy/GiphyAPI