I am trying to make a CLI client for an API. Once the user logs in to the API (via a login command on the CLI) the API creates a session and issues a cookie with a Max-Age/Expiry.
In the client, ideally, I'd like to get this cookie, persist it to disk and use it as long as it isn't expired. I am using the net/http/cookiejar and https://github.com/nhatthm/go-cookiejar for persistence. But now I feel a bit stuck because all cookies in the Jar have a Expiry of 0001-01-01 00:00:00 +0000 UTC or Max-Age of 0. Even though the persisted file is showing an Expires entry.
I tried to simply check the cookie right after I make the request which would set it to see if the problem lied in the 3rd party library but the jar also didn't store any information on the Cookie expiry and I also got the 0001-01-01 00:00:00 +0000 UTC.
Example code of the above mentioned test:
func (c *Client) SetupJar() {
jar, err := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
if err != nil {
log.Panic(err)
}
c.Http.Jar = jar
}
func (c *Client) foo() {
fmt.Println("Cookies before request")
for _, c := range c.Http.Jar.Cookies(u) {
fmt.Println(c, c.Expires, c.Path)
}
// Request done here
fmt.Println("Cookies after request")
for _, c := range c.Http.Jar.Cookies(u) {
fmt.Println(c, c.Expires, c.Path)
}
}
Which outputs:
Cookies before request
Cookies after request
session=MJe4jKguS4TWcafwbDauJxsVdN4DibnHVknddXzOyGU.bc6dO7-zrhWfv4yl2SXSE0KaKtQ 0001-01-01 00:00:00 +0000 UTC
Even the c.Path is empty
The persisted file (if this is ran using the 3rd party library) has everything however:
{
"localhost": {
"localhost;/;session": {
"Name": "session",
"Value": "MJe4jKguS4TWcafwbDauJxsVdN4DibnHVknddXzOyGU.bc6dO7-zrhWfv4yl2SXSE0KaKtQ",
"Quoted": false,
"Domain": "localhost",
"Path": "/",
"SameSite": "",
"Secure": false,
"HttpOnly": true,
"Persistent": true,
"HostOnly": true,
"Expires": "2024-10-11T15:53:14Z",
"Creation": "2024-10-11T16:52:45.000924497+01:00",
"LastAccess": "2024-10-11T16:52:45.000924497+01:00",
"SeqNum": 0
}
}
}
What am I missing here?
The Cookies method is not required to populate the Expires field (because it is not relevant when sending cookies).
github.com/nhatthm/go-cookiejar's implementation ends with
for _, e := range selected {
cookies = append(cookies, &http.Cookie{Name: e.Name, Value: e.Value, Quoted: e.Quoted})
}
return cookies
That's why you don't see the expiration time in your debugging output. It's fine, however. The jar works as expected and will not send expired cookies.