Created
February 28, 2024 20:06
-
-
Save M41KL-N41TT/ca5631666c509fa7a0353bf15753445a to your computer and use it in GitHub Desktop.
how to filter out cookies by name or by value when looping over a slice of cookies obtained from an http.Response object.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"net/http" | |
) | |
func main() { | |
// Assuming `resp` is an http.Response object from which you've got the cookies. | |
// Replace `resp` with the actual response object from your HTTP request. | |
resp := &http.Response{} // Placeholder. Use your actual *http.Response here. | |
// Get cookies from the response. | |
cookies := resp.Cookies() | |
// Loop over the cookies. | |
for i := 0; i < len(cookies); { | |
// If the cookie name matches a certain condition, the value is "deleted", or is meant to be deleted (you should define this condition), | |
// then delete the cookie from the slice. | |
// Adjust the condition as necessary, including how you determine if a cookie is "meant to be deleted". | |
if cookies[i].Name == "SpecificCookieName" || cookies[i].Value == "deleted" { | |
// Delete the cookie by filtering it out of the slice. | |
cookies = append(cookies[:i], cookies[i+1:]...) | |
} else { | |
// Only increment `i` if no deletion occurred to avoid skipping elements. | |
i++ | |
} | |
} | |
// At this point, `cookies` contains only the cookies that aren't matched by the condition above. | |
// Use `cookies` as needed from here on. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment