package inner import ( "bytes" "fmt" "io" "net/http" "stat/common/crypt" "stat/common/stdLog" "github.com/gin-gonic/gin" ) type cWriter struct { gin.ResponseWriter body *bytes.Buffer } func (w *cWriter) Write(b []byte) (int, error) { return w.body.Write(b) } func (w *cWriter) WriteString(s string) (int, error) { return w.body.WriteString(s) } func Crypt(key string) gin.HandlerFunc { return func(c *gin.Context) { // decrypt raw, err := c.GetRawData() if err != nil { c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{ "code": stdLog.Failure, "msg": fmt.Sprintf("读取Body数据出错: %s", err.Error()), }) return } de, err := crypt.CoreAesDecryptEx(raw, 12, key) if err != nil { c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{ "code": stdLog.Failure, "msg": fmt.Sprintf("解密Body数据出错: %s", err.Error()), }) return } c.Request.Body = io.NopCloser(bytes.NewBuffer(de)) c.Request.ContentLength = int64(len(de)) c.Request.Header.Set("Content-Type", "application/json") oWriter := c.Writer blw := &cWriter{body: bytes.NewBufferString(""), ResponseWriter: c.Writer} c.Writer = blw c.Next() // encrypt c.Writer = oWriter en, err := crypt.CoreAesEncryptEx(blw.body.Bytes(), 12, key) if err != nil { c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{ "code": stdLog.Failure, "msg": fmt.Sprintf("加密Body数据出错: %s", err.Error()), }) return } _, err = c.Writer.Write(en) if err != nil { c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{ "code": stdLog.Failure, "msg": fmt.Sprintf("写入Body数据出错: %s", err.Error()), }) return } } }