@@ -12,7 +12,6 @@ import (
1212 "fmt"
1313 "net/http"
1414 "net/http/cookiejar"
15- "net/url"
1615 "strings"
1716
1817 "github.com/deploymenttheory/go-api-http-client/logger"
@@ -32,6 +31,35 @@ func SetupCookieJar(client *http.Client, enableCookieJar bool, log logger.Logger
3231 return nil
3332}
3433
34+ // GetCookies is a middleware that extracts cookies from incoming requests and serializes them.
35+ func GetCookies (next http.Handler , log logger.Logger ) http.Handler {
36+ return http .HandlerFunc (func (w http.ResponseWriter , r * http.Request ) {
37+
38+ // Extract cookies from the request
39+ cookies := r .Cookies ()
40+
41+ // Serialize the cookies
42+ serializedCookies := SerializeCookies (cookies )
43+
44+ // Log the serialized cookies
45+ log .Info ("Serialized Cookies" , zap .String ("Cookies" , serializedCookies ))
46+
47+ // Call the next handler in the chain
48+ next .ServeHTTP (w , r )
49+ })
50+ }
51+
52+ // SerializeCookies serializes a slice of *http.Cookie into a string format.
53+ func SerializeCookies (cookies []* http.Cookie ) string {
54+ var cookieStrings []string
55+
56+ for _ , cookie := range cookies {
57+ cookieStrings = append (cookieStrings , cookie .String ())
58+ }
59+
60+ return strings .Join (cookieStrings , "; " )
61+ }
62+
3563// RedactSensitiveCookies redacts sensitive information from cookies.
3664// It takes a slice of *http.Cookie and returns a redacted slice of *http.Cookie.
3765func RedactSensitiveCookies (cookies []* http.Cookie ) []* http.Cookie {
@@ -74,28 +102,3 @@ func ParseCookieHeader(header string) *http.Cookie {
74102 }
75103 return nil
76104}
77-
78- // PrintCookies prints the cookies stored in the HTTP client's cookie jar for a given URL.
79- func PrintCookies (client * http.Client , urlString string , log logger.Logger ) {
80- if client .Jar == nil {
81- log .Error ("Cookie jar is not initialized." )
82- return
83- }
84-
85- // Correctly use url.Parse for parsing the URL string
86- parsedURL , err := url .Parse (urlString )
87- if err != nil {
88- log .Error ("Failed to parse URL for cookie jar" , zap .Error (err ))
89- return
90- }
91-
92- cookies := client .Jar .Cookies (parsedURL )
93- if len (cookies ) == 0 {
94- log .Info ("No cookies found for URL" , zap .String ("url" , urlString ))
95- return
96- }
97-
98- for _ , cookie := range cookies {
99- log .Info ("Cookie" , zap .String ("Name" , cookie .Name ), zap .String ("Value" , cookie .Value ))
100- }
101- }
0 commit comments