Created
November 6, 2019 12:17
-
-
Save yqt/a9d85205df98b275bbaac26f7ad48023 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"github.com/patrickmn/go-cache" | |
"github.com/gin-gonic/gin" | |
"log" | |
"time" | |
) | |
func Logger() gin.HandlerFunc { | |
return func(c *gin.Context) { | |
t := time.Now() | |
// Set example variable | |
c.Set("example", "12345") | |
// before request | |
c.Next() | |
// after request | |
latency := time.Since(t) | |
log.Print(latency) | |
// access the status we are sending | |
status := c.Writer.Status() | |
log.Println(status) | |
} | |
} | |
func Cacher(ca *cache.Cache) gin.HandlerFunc { | |
return func(c *gin.Context) { | |
c.Set("cache", ca) | |
} | |
} | |
func main() { | |
ca1 := cache.New(5*time.Minute, 10*time.Minute) | |
r := gin.New() | |
r.Use(Logger()) | |
r.Use(Cacher(ca1)) | |
r.GET("/test", func(c *gin.Context) { | |
ca := c.MustGet("cache").(*cache.Cache) | |
ca.Set("foo", "bar", cache.DefaultExpiration) | |
example := c.MustGet("example").(string) | |
// it would print: "12345" | |
log.Println(example) | |
}) | |
r.GET("/test1", func(c *gin.Context) { | |
ca := c.MustGet("cache").(*cache.Cache) | |
foo, found := ca.Get("foo") | |
if found { | |
log.Println(foo) | |
} else { | |
log.Println("not found") | |
} | |
}) | |
// Listen and serve on 0.0.0.0:8080 | |
r.Run(":8080") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment