-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
76 lines (61 loc) · 1.48 KB
/
main.go
File metadata and controls
76 lines (61 loc) · 1.48 KB
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
package main
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
)
type giphyResponse struct {
Data struct {
Images struct {
DownsizedStill struct {
URL string `json:"url"`
} `json:"downsized_still"`
} `json:"images"`
} `json:"data"`
}
func getGIF(key string) (string, error) {
client := &http.Client{}
url := fmt.Sprintf("https://api.giphy.com/v1/gifs/random?api_key=%s&tag=&rating=G", key)
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return "", err
}
resp, err := client.Do(req)
if err != nil {
return "", err
}
if resp.StatusCode != http.StatusOK {
return "", errors.New("http status code not OK")
}
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
defer resp.Body.Close()
response := &giphyResponse{}
if err := json.Unmarshal(data, response); err != nil {
return "", err
}
return response.Data.Images.DownsizedStill.URL, nil
}
func handler(w http.ResponseWriter, r *http.Request) {
gifURL, err := getGIF(os.Getenv("GIPHY_TOKEN"))
if err != nil {
log.Printf("error: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Add("Content-Type", "text/html")
fmt.Fprintf(w, `<html><img src="%s"></html>`, gifURL)
}
func main() {
http.HandleFunc("/", handler)
http.HandleFunc("/favicon.ico", http.NotFound)
log.Println("Starting server...")
log.Println("http://localhost:1234")
log.Fatalln(http.ListenAndServe(":1234", nil))
}