summaryrefslogtreecommitdiff
path: root/jsonClient.go
blob: 4dc9b1083764e103769d45dea507b5526f19910f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
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)
*/