package main import ( "bytes" "encoding/json" "io/ioutil" "net/http" ) // RequestInfo holds the extracted data from http.Request type RequestInfo struct { Host string `json:"host"` URL string `json:"url"` Proto string `json:"proto"` Addr string `json:"addr"` Agent string `json:"agent"` Headers map[string][]string `json:"headers"` Cookies map[string]string `json:"cookies"` QueryParams map[string][]string `json:"queryParams"` // Add other fields as needed Body string `json:"body"` } // dumpClient returns a string with JSON formatted http.Request information func dumpJsonClient(r *http.Request) (string, error) { // Extracting Cookies cookieMap := make(map[string]string) for _, cookie := range r.Cookies() { cookieMap[cookie.Name] = cookie.Value } // Read the body (Ensure to do this first) var bodyBytes []byte if r.Body != nil { // Read the body if it's not nil bodyBytes, _ = ioutil.ReadAll(r.Body) r.Body.Close() // Close the body when done reading r.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes)) // Reset the body } info := RequestInfo{ Host: r.Host, URL: r.URL.String(), Proto: r.Proto, Addr: r.RemoteAddr, Agent: r.UserAgent(), Headers: r.Header, Cookies: cookieMap, QueryParams: r.URL.Query(), Body: string(bodyBytes), } // Marshal the struct to a JSON string jsonString, err := json.Marshal(info) if err != nil { return "", err // Return the error to the caller } var jsonData interface{} err = json.Unmarshal([]byte(jsonString), &jsonData) if err != nil { return "", err // Return the error to the caller } formattedJSON, err := json.MarshalIndent(jsonData, "", " ") if err != nil { return "", err // Return the error to the caller } return string(formattedJSON), nil } /* package main import ( "bytes" "encoding/json" "io" "io/ioutil" "net/http" ) type RequestInfo struct { // ... (other fields) Body string `json:"body"` // ... (other fields) } func dumpClient(r *http.Request) (string, error) { // ... (rest of your code to collect other request info) info := RequestInfo{ // ... (other fields) Body: string(bodyBytes), // ... (other fields) } // Marshal the struct to a JSON string jsonString, err := json.Marshal(info) if err != nil { return "", err } return string(jsonString), nil } // ... (rest of your code) */