|
| 1 | +package httpclient |
| 2 | + |
| 3 | +import ( |
| 4 | + "net/http" |
| 5 | + "strings" |
| 6 | +) |
| 7 | + |
| 8 | +// RedactSensitiveCookies redacts sensitive information from cookies. |
| 9 | +// It takes a slice of *http.Cookie and returns a redacted slice of *http.Cookie. |
| 10 | +func RedactSensitiveCookies(cookies []*http.Cookie) []*http.Cookie { |
| 11 | + // Define sensitive cookie names that should be redacted. |
| 12 | + sensitiveCookieNames := map[string]bool{ |
| 13 | + "SessionID": true, // Example sensitive cookie name |
| 14 | + // Add more sensitive cookie names as needed. |
| 15 | + } |
| 16 | + |
| 17 | + // Iterate over the cookies and redact sensitive ones. |
| 18 | + for _, cookie := range cookies { |
| 19 | + if _, found := sensitiveCookieNames[cookie.Name]; found { |
| 20 | + cookie.Value = "REDACTED" |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + return cookies |
| 25 | +} |
| 26 | + |
| 27 | +// Utility function to convert cookies from http.Header to []*http.Cookie. |
| 28 | +// This can be useful if cookies are stored in http.Header (e.g., from a response). |
| 29 | +func CookiesFromHeader(header http.Header) []*http.Cookie { |
| 30 | + cookies := []*http.Cookie{} |
| 31 | + for _, cookieHeader := range header["Set-Cookie"] { |
| 32 | + if cookie := ParseCookieHeader(cookieHeader); cookie != nil { |
| 33 | + cookies = append(cookies, cookie) |
| 34 | + } |
| 35 | + } |
| 36 | + return cookies |
| 37 | +} |
| 38 | + |
| 39 | +// ParseCookieHeader parses a single Set-Cookie header and returns an *http.Cookie. |
| 40 | +func ParseCookieHeader(header string) *http.Cookie { |
| 41 | + headerParts := strings.Split(header, ";") |
| 42 | + if len(headerParts) > 0 { |
| 43 | + cookieParts := strings.SplitN(headerParts[0], "=", 2) |
| 44 | + if len(cookieParts) == 2 { |
| 45 | + return &http.Cookie{Name: cookieParts[0], Value: cookieParts[1]} |
| 46 | + } |
| 47 | + } |
| 48 | + return nil |
| 49 | +} |
0 commit comments