Advertisement
Grork

Go autocomplete

Jan 23rd, 2017
340
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.04 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "gopkg.in/gin-gonic/gin.v1"
  5.     "net/http"
  6.     "io/ioutil"
  7.     "github.com/patrickmn/go-cache"
  8.     "time"
  9. )
  10.  
  11. func main() {
  12.  
  13.     // Routes
  14.     gin.SetMode(gin.ReleaseMode)
  15.     r := gin.Default()
  16.  
  17.     // Set cache default expiring to 30days and which purges expired items every 24h
  18.     c := cache.New((24 * time.Hour) * 30 * 6, 24 * time.Hour)
  19.    
  20.     r.GET("/autocomplete/company/:term", func(g *gin.Context) {
  21.         term := g.Param("term")
  22.        
  23.         // Check if in cache
  24.         item, cached := c.Get("autocomplete-company-" + term)
  25.        
  26.         if cached {
  27.             g.String(200, item.(string))
  28.             return
  29.         }
  30.  
  31.         res, err := http.Get("https://autocomplete.clearbit.com/v1/companies/suggest?query=" + term)
  32.         if err != nil {
  33.             panic(err.Error())
  34.         }
  35.        
  36.         defer res.Body.Close()
  37.         body, err := ioutil.ReadAll(res.Body)
  38.         results := string(body)
  39.  
  40.         // Save in cache
  41.         c.Set("autocomplete-company-" + term, results, cache.DefaultExpiration)
  42.         g.String(200, results)
  43.     })
  44.  
  45.     r.Run(":1234")
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement