智盟项目
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

mw_request_cache.go 1.5 KiB

1 jaar geleden
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package mw
  2. import (
  3. "applet/app/e"
  4. "applet/app/md"
  5. "applet/app/utils"
  6. "applet/app/utils/cache"
  7. "bytes"
  8. "fmt"
  9. "github.com/gin-gonic/gin"
  10. "io/ioutil"
  11. )
  12. //自己实现一个type gin.ResponseWriter interface
  13. type responseWriter struct {
  14. gin.ResponseWriter
  15. b *bytes.Buffer
  16. }
  17. //重写Write([]byte) (int, error)
  18. func (w responseWriter) Write(b []byte) (int, error) {
  19. //向一个bytes.buffer中再写一份数据
  20. w.b.Write(b)
  21. //完成gin.Context.Writer.Write()原有功能
  22. return w.ResponseWriter.Write(b)
  23. }
  24. // RequestCache is cache middleware
  25. func RequestCache(c *gin.Context) {
  26. tempMasterId, _ := c.Get("master_id")
  27. masterId := tempMasterId.(string)
  28. uri := c.Request.RequestURI
  29. md5Params := dealBodyParams(c)
  30. cacheKey := fmt.Sprintf(md.ZhimengDataRequestCacheKey, masterId, uri, md5Params)
  31. //自己实现一个type gin.ResponseWriter
  32. writer := responseWriter{
  33. c.Writer,
  34. bytes.NewBuffer([]byte{}),
  35. }
  36. isUse, _ := cache.GetInt(md.ZhimengIsUseCacheKey)
  37. var res = map[string]interface{}{}
  38. cache.GetJson(cacheKey, &res)
  39. if res["data"] != nil && isUse == 1 {
  40. e.OutSuc(c, res["data"], nil)
  41. return
  42. }
  43. c.Writer = writer
  44. c.Next()
  45. }
  46. func dealBodyParams(c *gin.Context) (md5Params string) {
  47. body, err := c.GetRawData()
  48. if err != nil {
  49. panic(err)
  50. }
  51. fmt.Println(">>>>>>>>>>string<<<<<<<<<<<", string(body))
  52. md5Params = utils.Md5(string(body))
  53. //TODO::把读过的字节流重新放到body
  54. c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(body))
  55. return
  56. }