captureRequestInfo extracts relevant information from the incoming HTTP request. It captures the URL, method, headers, and body. The request body is read and then restored so that it can be processed by subsequent handlers.
(c *gin.Context, captureBody bool)
| 141 | // It captures the URL, method, headers, and body. The request body is read and then |
| 142 | // restored so that it can be processed by subsequent handlers. |
| 143 | func captureRequestInfo(c *gin.Context, captureBody bool) (*RequestInfo, error) { |
| 144 | // Capture URL with sensitive query parameters masked |
| 145 | maskedQuery := util.MaskSensitiveQuery(c.Request.URL.RawQuery) |
| 146 | url := c.Request.URL.Path |
| 147 | if maskedQuery != "" { |
| 148 | url += "?" + maskedQuery |
| 149 | } |
| 150 | |
| 151 | // Capture method |
| 152 | method := c.Request.Method |
| 153 | |
| 154 | // Capture headers |
| 155 | headers := make(map[string][]string) |
| 156 | for key, values := range c.Request.Header { |
| 157 | headers[key] = values |
| 158 | } |
| 159 | |
| 160 | // Capture request body |
| 161 | var body []byte |
| 162 | if captureBody && c.Request.Body != nil { |
| 163 | // Read the body |
| 164 | bodyBytes, err := io.ReadAll(c.Request.Body) |
| 165 | if err != nil { |
| 166 | return nil, err |
| 167 | } |
| 168 | |
| 169 | // Restore the body for the actual request processing |
| 170 | c.Request.Body = io.NopCloser(bytes.NewBuffer(bodyBytes)) |
| 171 | body = decodeCapturedRequestBodyForLog(bodyBytes, c.Request.Header.Get("Content-Encoding")) |
| 172 | } |
| 173 | |
| 174 | return &RequestInfo{ |
| 175 | URL: url, |
| 176 | Method: method, |
| 177 | Headers: headers, |
| 178 | Body: body, |
| 179 | RequestID: logging.GetGinRequestID(c), |
| 180 | Timestamp: time.Now(), |
| 181 | }, nil |
| 182 | } |
| 183 | |
| 184 | func decodeCapturedRequestBodyForLog(raw []byte, encoding string) []byte { |
| 185 | if len(raw) == 0 { |