My application relies on cookies and I want to test my user's browser to see if it accepts cookies. I use one middle ware to set a test cookie and another one to read the cookie. It looks like the cookie does not get set to begin with so there is nothing to read.
package main
import (
"fmt"
"log"
"net/http"
"time"
"github.com/gorilla/mux"
)
var testCookieName = "testCookieName"
var testCookieValue = "12345"
func setTestCookie(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
//testCookieName = "testCookieName" //genUUID()
//testCookieValue = "12345" //genUUID()
cookie := http.Cookie{}
cookie.Name = testCookieName
cookie.Value = testCookieValue
cookie.MaxAge = time.Now().Minute() * 60
//cookie.Domain = config.Domain
cookie.Path = "/"
cookie.Secure = false //true
cookie.HttpOnly = false //true
next.ServeHTTP(w, r)
})
}
func getTestCookie(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tokenCookie, err := r.Cookie(testCookieName)
if err != nil {
fmt.Println(err.Error())
http.Redirect(w, r, "/cookiefail", http.StatusTemporaryRedirect)
return
}
fmt.Println(testCookieName)
fmt.Println(testCookieValue)
fmt.Println(tokenCookie.Value)
if testCookieValue != tokenCookie.Value {
http.Redirect(w, r, "/cookiefail", http.StatusTemporaryRedirect)
return
}
next.ServeHTTP(w, r)
})
}
func main() {
router := mux.NewRouter()
router.Use(setTestCookie)
router.Use(getTestCookie)
router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, world!"))
})
s := &http.Server{
Addr: ":7088",
Handler: router,
}
log.Fatal(s.ListenAndServe())
}
Any idea to what is wrong with my code or suggestion for another method?
setTestCookie
is not setting any cookie. All it does is create a variable of a struct type, populate its fields, and that's it. Also trying to set the cookie with middleware indiscriminately is just wrong. Generally you set a cookie after some specific event occurs, like a successful login, and you set it by writing it into the response's header. Once done correctly, the browser, upon receiving the response, remembers that cookie and sends it in the header of every subsequent request. - mkopriva