// Package middleware ...
//
// Description : middleware ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2024-07-26 11:54
package middleware

import (
	"git.zhangdeman.cn/zhangdeman/gin/define"
	"git.zhangdeman.cn/zhangdeman/gin/request"
	"github.com/gin-gonic/gin"
)

type HookFunc func(ctx *gin.Context, requestData []byte, responseData map[string]interface{}, cost int64)

// HookAfterResponseMiddleware 请求最终处理完成之后执行的中间件
func HookAfterResponseMiddleware(hookFunc HookFunc) gin.HandlerFunc {
	handleConfig := define.GetHttpHandleConfig()
	return func(ctx *gin.Context) {
		ctx.Next()
		if nil == hookFunc {
			return
		}
		// hook 不为nil, 自动触发
		hookFunc(
			ctx,
			[]byte(ctx.GetString(handleConfig.RecordRequestDataField)),
			ctx.GetStringMap(handleConfig.RecordResponseDataField),
			request.WrapperHandle.GetCtxIntData(ctx, handleConfig.FinishRequestTimeField, 0)-request.WrapperHandle.GetCtxIntData(ctx, handleConfig.StartRequestTimeField, 0),
		)
	}
}
