I’m fairly new to Go (but I’m loving it) but I’ve noticed a really strange behavior when trying to check for cookies that don’t exist. Basically my app spins out of control and it wont serve up any more pages. I for the life of me can’t figure out why. At first I thought it may have been a redirect loop, as I was checking cookies to validate authentication, but even without a http.Redirect it happens.
I worked with PHP many years ago and I never saw anything like this. The counter variable i doesn’t increment but clearly the function if firing over and over.
Here is my code for the function that tries to read the cookies
func TestCookieCheck(w http.ResponseWriter, r *http.Request) {
cookie1, err1 := r.Cookie("emailValue")
cookie2, err2 := r.Cookie("authValue")
i := 0
if err1 == nil && err2 == nil {
//pass = true
println("Cookies exist")
} else {
print(i)
print(" ")
println("model userauth TestCookiesCheck - cookies do not exist")
i++
//http.Redirect(w, r, "/login/", http.StatusTemporaryRedirect)
}
println(cookie1.Value)
println(cookie2.Value)
}
You’re serving something back to the browser. Does it link to images, resources, etc? Favicon.ico comes for free. You can print the requested path in the handler to see what it is.
Oh man you were spot on, I printed out the request path and it’s being called over and over. This doesn’t happen when I’m not testing for cookies, it does happen when I do test for cookies.
Is there a proper way to pass your request object to cookies so I don’t end up in some crazy loop? When I look at the golang documentation is just shows the example of passing ‘r’ do the method.
This is what I’m (completely) guessing is what’s happening:
I’m passing in my raw request object into the function from my page. I’m then using that request object to try and pull off the value of the cookie. Is Go just recreating that whole request object every time? If so I can see why this could cause a infinite loop, but man that just seems like a REALLY buggy way of handling things.
Is Go just recreating that whole request object every time?
No. r is a pointer to the actual http.Request. r gets copied, but it just tells where the http.Request is found in memory.
The counter variable i doesn’t increment but clearly the function if firing over and over.
The counter, i, only exists for the execution of TestCookieCheck. Each new run gets its own i.
Oh man you were spot on, I printed out the request path and it’s being called over and over. This doesn’t happen when I’m not testing for cookies, it does happen when I do test for cookies.
@calmh suggested that the browser was making the requests. You can test this by making the requests using curl. Passing -v to it will make curl tell you everything it does (including multiple requests, following redirects, etc).
Thing to note about making requests that fall through in golang, the browser will retry getting the requested info unless you send it an appropriate response Status.