8058
Ir
irvc / files
irvc / giphy.go
1.6 KB
1package main 2 3import ( 4 "encoding/json" 5 "net/http" 6 "net/url" 7 "strconv" 8 "time" 9 10 "github.com/gin-gonic/gin" 11) 12 13const gifLimit = 6 14 15type gif struct { 16 URL string `json:"url"` 17 Preview string `json:"preview"` 18} 19 20func (s *Server) handleGifs(c *gin.Context) { 21 if s.cfg.GiphyKey == "" { 22 c.JSON(http.StatusServiceUnavailable, gin.H{"error": "gifs disabled"}) 23 return 24 } 25 query := c.Query("q") 26 endpoint := "https://api.giphy.com/v1/gifs/trending" 27 if query != "" { 28 endpoint = "https://api.giphy.com/v1/gifs/search" 29 } 30 u, err := url.Parse(endpoint) 31 if err != nil { 32 c.JSON(http.StatusInternalServerError, gin.H{"error": "giphy"}) 33 return 34 } 35 params := u.Query() 36 params.Set("api_key", s.cfg.GiphyKey) 37 params.Set("limit", strconv.Itoa(gifLimit)) 38 params.Set("rating", "pg-13") 39 if query != "" { 40 params.Set("q", query) 41 } 42 u.RawQuery = params.Encode() 43 44 client := &http.Client{Timeout: 5 * time.Second} 45 resp, err := client.Get(u.String()) 46 if err != nil { 47 c.JSON(http.StatusBadGateway, gin.H{"error": "giphy"}) 48 return 49 } 50 defer resp.Body.Close() 51 var body struct { 52 Data []struct { 53 Images struct { 54 Original struct{ URL string } `json:"original"` 55 FixedHeight struct{ URL string } `json:"fixed_height"` 56 } `json:"images"` 57 } `json:"data"` 58 } 59 if err := json.NewDecoder(resp.Body).Decode(&body); err != nil { 60 c.JSON(http.StatusBadGateway, gin.H{"error": "giphy"}) 61 return 62 } 63 gifs := make([]gif, 0, len(body.Data)) 64 for _, g := range body.Data { 65 gifs = append(gifs, gif{URL: g.Images.Original.URL, Preview: g.Images.FixedHeight.URL}) 66 } 67 c.JSON(http.StatusOK, gin.H{"gifs": gifs}) 68}