package mw import ( "applet/app/e" "applet/app/md" "applet/app/utils" "applet/app/utils/cache" "bytes" "fmt" "github.com/gin-gonic/gin" "io/ioutil" ) // 自己实现一个type gin.ResponseWriter interface type responseWriter struct { gin.ResponseWriter b *bytes.Buffer } // 重写Write([]byte) (int, error) func (w responseWriter) Write(b []byte) (int, error) { //向一个bytes.buffer中再写一份数据 w.b.Write(b) //完成gin.Context.Writer.Write()原有功能 return w.ResponseWriter.Write(b) } // RequestCache is cache middleware func RequestCache(c *gin.Context) { tempMasterId, _ := c.Get("master_id") masterId := tempMasterId.(string) uri := c.Request.RequestURI md5Params := dealBodyParams(c) cacheKey := fmt.Sprintf(md.ZhimengDataRequestCacheKey, masterId, uri, md5Params) //自己实现一个type gin.ResponseWriter writer := responseWriter{ c.Writer, bytes.NewBuffer([]byte{}), } isUse, _ := cache.GetInt(md.ZhimengIsUseCacheKey) var res = map[string]interface{}{} cache.GetJson(cacheKey, &res) if res["data"] != nil && isUse == 1 { e.OutSuc(c, res["data"], nil) return } c.Writer = writer c.Next() } func dealBodyParams(c *gin.Context) (md5Params string) { body, err := c.GetRawData() if err != nil { panic(err) } fmt.Println(">>>>>>>>>>string<<<<<<<<<<<", string(body)) md5Params = utils.Md5(string(body)) //TODO::把读过的字节流重新放到body c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(body)) return }