package middleware import ( "bytes" "encoding/json" "io/ioutil" "simple-memo/utils" "github.com/gin-gonic/gin" "go.uber.org/zap" "simple-memo/global" ) func Encryption() gin.HandlerFunc { return func(c *gin.Context) { // 只处理POST if c.Request.Method == "POST" { body, err := ioutil.ReadAll(c.Request.Body) if err != nil { global.Logger.Error("读取请求体失败", append(utils.LogContextFields(c), zap.Error(err))..., ) utils.Fail(c, "读取请求体失败") c.Abort() return } if len(body) == 0 { utils.Fail(c, "请求体为空") c.Abort() return } // 解析 {data:"加密串"} var req map[string]string if err = json.Unmarshal(body, &req); err != nil { global.Logger.Error("解析请求体失败", append(utils.LogContextFields(c), zap.Error(err))..., ) utils.Fail(c, "参数格式错误") c.Abort() return } encryptedData, ok := req["data"] if !ok { utils.Fail(c, "参数格式错误") c.Abort() return } baseFields := utils.LogContextFields(c) // ====================== 日志:打印【加密串】 ====================== global.Logger.Info("【请求加密数据】", append(baseFields, zap.String("encrypt_data", encryptedData), )..., ) // 解密 decrypted, err := utils.AESDecrypt(encryptedData) if err != nil { utils.Fail(c, "解密失败") c.Abort() return } // ====================== 日志:打印【解密后的明文】 ====================== global.Logger.Info("【请求解密明文】", append(baseFields, zap.String("decrypt_data", string(decrypted)), )..., ) // 重新赋值给Body c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(decrypted)) } c.Next() } }