This commit is contained in:
Yun
2024-06-25 18:34:00 +08:00
commit 9a2daa7ff7
8 changed files with 367 additions and 0 deletions
+25
View File
@@ -0,0 +1,25 @@
package middleware
import (
"net/http"
"github.com/gin-gonic/gin"
)
func Cors() gin.HandlerFunc {
return func(ctx *gin.Context) {
method := ctx.Request.Method
ctx.Header("Access-Control-Allow-Origin", "*")
// ctx.Header("Access-Control-Allow-Headers","Content-Type,AccessToken,X-CSRF-Token,Authorization,Token")
ctx.Header("Access-Control-Allow-Methods", "POST,GET,OPTIONS")
// ctx.Header("Access-Control-Allow-Headers","Content-Length,Access-Control-Allow-Origin,Access-Control-Allow-Headers,Content-Type")
ctx.Header("Access-Control-Allow-Credentials", "true")
ctx.Header("Access-Control-Allow-Headers", "*")
if method == "OPTIONS" {
ctx.AbortWithStatus(http.StatusNoContent)
return
}
ctx.Next()
}
}
+38
View File
@@ -0,0 +1,38 @@
package middleware
import (
"bytes"
"fmt"
"github.com/gin-gonic/gin"
)
// 原理是创建的时候注入了一个方法处理响应的信息
func ResponseFilterMiddleware(c *gin.Context) {
fmt.Println(c.Writer)
blw := &bodyLogWriter{
body: bytes.NewBufferString(""),
ResponseWriter: c.Writer,
}
c.Writer = blw
c.Next()
statusCode := c.Writer.Status()
fmt.Println(statusCode)
fmt.Println("拦截输出")
}
type bodyLogWriter struct {
gin.ResponseWriter
body *bytes.Buffer
}
// 真正输出的时候,它会调用这个输出方法
func (w bodyLogWriter) Write(b []byte) (int, error) {
// b = []byte(`{"code":0}`)
w.body.Write(b)
return w.ResponseWriter.Write(b)
}
+37
View File
@@ -0,0 +1,37 @@
package middleware
import (
"fmt"
"github.com/gin-gonic/gin"
)
func LoggerFormat() gin.HandlerFunc {
return gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
// 你的自定义格式
return fmt.Sprintf("[VISIT] UUID:%s | IP:%s | 时间:%s | 方法:%s | 路径:%s | 协议:%s | 状态码:%d | 耗时:%s | 代理头:%s | 错误信息:%s \n",
// UUID
param.Keys["uuid"],
//客户端IP
param.ClientIP,
//时间格式
param.TimeStamp.Format("2006-01-02 15:04:05"),
//http请求方式 get post等
param.Method,
//客户端请求的路径
param.Path,
//http请求协议版本
param.Request.Proto,
//http请求状态码
param.StatusCode,
//请求耗时
param.Latency,
//http请求代理头
param.Request.UserAgent(),
//处理请求错误时设置错误消息
param.ErrorMessage,
)
})
}
+24
View File
@@ -0,0 +1,24 @@
package middleware
import (
"code.yun.ink/pkg/limitx"
"github.com/gin-gonic/gin"
)
func LimiterMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// 获取IP(待封装)
ipAddr := "127.0.0.1"
// c.Request.RemoteAddr
limiter := limitx.RateLimiter.GetLimiter(ipAddr)
if !limiter.Allow() {
c.JSON(400, gin.H{"code": 400, "message": "访问频率超出限制"})
c.Abort()
return
} else {
c.Next()
}
return
}
}
+108
View File
@@ -0,0 +1,108 @@
package middleware
import (
"bytes"
"encoding/json"
"io"
"log"
"strings"
"github.com/gin-gonic/gin"
)
// 打印请求参数和响应参数
func LoggerParams() gin.HandlerFunc {
return func(ctx *gin.Context) {
buf := &bytes.Buffer{}
tea := io.TeeReader(ctx.Request.Body, buf)
body, err := io.ReadAll(tea)
if err != nil {
log.Panicf("read body err:%+v", err)
}
ctx.Request.Body = io.NopCloser(buf)
// 下面是响应参数缓存
blw := &bodyParamsWriter{
body: bytes.NewBufferString(""),
ResponseWriter: ctx.Writer,
}
ctx.Writer = blw
ctx.Next()
// 判断返回的值是否json
contentType := ctx.Writer.Header().Get("Content-Type")
if !strings.Contains(contentType, "application/json") {
return
}
resp := blw.body.String()
m := map[string]interface{}{
"trace_id": ctx.Keys["trace_id"],
"method": ctx.Request.Method,
"path": ctx.FullPath(),
"client_ip": ctx.ClientIP(),
"body": string(body),
"response": resp,
"request_header": ctx.Request.Header,
"response_code": ctx.Writer.Status(),
}
b, _ := json.Marshal(m)
log.Println(string(b))
}
// return gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
// buf := &bytes.Buffer{}
// tea := io.TeeReader(param.Request.Body, buf)
// body, err := ioutil.ReadAll(tea)
// if err != nil {
// log.Panicf("read body err:%+v", err)
// }
// param.Request.Body = io.NopCloser(buf)
// fmt.Println("ddddd",string(body))
// // 你的自定义格式
// return fmt.Sprintf("[VISIT] trace_id:%s | 参数:%s | IP:%s | 时间:%s | 方法:%s | 路径:%s | 协议:%s | 状态码:%d | 耗时:%s | 代理头:%s | 错误信息:%s \n",
// // trace_id
// param.Keys["trace_id"],
// body,
// //客户端IP
// param.ClientIP,
// //时间格式
// param.TimeStamp.Format("2006-01-02 15:04:05"),
// //http请求方式 get post等
// param.Method,
// //客户端请求的路径
// param.Path,
// //http请求协议版本
// param.Request.Proto,
// //http请求状态码
// param.StatusCode,
// //请求耗时
// param.Latency,
// //http请求代理头
// param.Request.UserAgent(),
// //处理请求错误时设置错误消息
// param.ErrorMessage,
// )
// })
}
type bodyParamsWriter struct {
gin.ResponseWriter
body *bytes.Buffer
}
// 真正输出的时候,它会调用这个输出方法
func (w bodyParamsWriter) Write(b []byte) (int, error) {
// b = []byte(`{"code":0}`)
w.body.Write(b)
return w.ResponseWriter.Write(b)
}
+13
View File
@@ -0,0 +1,13 @@
package middleware
import (
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
func SetTraceId() gin.HandlerFunc {
return func(ctx *gin.Context) {
u, _ := uuid.NewUUID()
ctx.Set("trace_id", u.String())
}
}