RequestDebugMiddleware 打印所有请求的详细信息,包括header、URL、body和query参数
()
| 12 | |
| 13 | // RequestDebugMiddleware 打印所有请求的详细信息,包括header、URL、body和query参数 |
| 14 | func RequestDebugMiddleware() gin.HandlerFunc { |
| 15 | return func(c *gin.Context) { |
| 16 | // 打印请求方法和URL |
| 17 | fmt.Printf("\n=== DEBUG REQUEST ===\n") |
| 18 | fmt.Printf("Method: %s\n", c.Request.Method) |
| 19 | fmt.Printf("URL: %s\n", c.Request.URL.String()) |
| 20 | fmt.Printf("Host: %s\n", c.Request.Host) |
| 21 | fmt.Printf("RemoteAddr: %s\n", c.Request.RemoteAddr) |
| 22 | |
| 23 | // 打印所有Header |
| 24 | fmt.Printf("\n--- Headers ---\n") |
| 25 | for key, values := range c.Request.Header { |
| 26 | for _, value := range values { |
| 27 | fmt.Printf("%s: %s\n", key, value) |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | // 打印Query参数 |
| 32 | if len(c.Request.URL.RawQuery) > 0 { |
| 33 | fmt.Printf("\n--- Query Parameters ---\n") |
| 34 | for key, values := range c.Request.URL.Query() { |
| 35 | for _, value := range values { |
| 36 | fmt.Printf("%s: %s\n", key, value) |
| 37 | } |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | // 读取并打印Body内容 |
| 42 | if c.Request.Body != nil { |
| 43 | // 读取Body内容 |
| 44 | bodyBytes, err := io.ReadAll(c.Request.Body) |
| 45 | if err == nil { |
| 46 | // 恢复Body,以便后续处理 |
| 47 | c.Request.Body = io.NopCloser(bytes.NewBuffer(bodyBytes)) |
| 48 | |
| 49 | // 尝试格式化JSON |
| 50 | var prettyJSON bytes.Buffer |
| 51 | if err := json.Indent(&prettyJSON, bodyBytes, "", " "); err == nil { |
| 52 | fmt.Printf("\n--- Body (JSON) ---\n%s\n", prettyJSON.String()) |
| 53 | } else { |
| 54 | // 如果不是JSON,直接打印原始内容 |
| 55 | fmt.Printf("\n--- Body (Raw) ---\n%s\n", string(bodyBytes)) |
| 56 | } |
| 57 | } else { |
| 58 | fmt.Printf("\n--- Body ---\nError reading body: %v\n", err) |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | // 打印表单数据(如果是表单提交) |
| 63 | if c.Request.Method == "POST" || c.Request.Method == "PUT" || c.Request.Method == "PATCH" { |
| 64 | contentType := c.GetHeader("Content-Type") |
| 65 | if strings.Contains(contentType, "multipart/form-data") || strings.Contains(contentType, "application/x-www-form-urlencoded") { |
| 66 | c.Request.ParseForm() |
| 67 | if len(c.Request.Form) > 0 { |
| 68 | fmt.Printf("\n--- Form Data ---\n") |
| 69 | for key, values := range c.Request.Form { |
| 70 | for _, value := range values { |
| 71 | fmt.Printf("%s: %s\n", key, value) |