net/http: invalid byte in Cookie.Value; dropping invalid bytes

411 views
Skip to first unread message

Tong Sun

unread,
Jul 21, 2023, 6:32:04 PM7/21/23
to golang-nuts
Hi Gophers, 

I'm facing a very weird error:

func getUserName(w http.ResponseWriter, r *http.Request) string {
c, err := r.Cookie("session")
if err != nil {
http.Redirect(w, r, rootUrl, http.StatusSeeOther)
return ""
}
log.Println("session raw", c.Value)

var s session
fmt.Printf("%+v\n", s)
reader := strings.NewReader(c.Value)
if err := gob.NewDecoder(reader).Decode(&s); err != nil {
log.Println(err)
http.Error(w, "server error: gob decoding", http.StatusInternalServerError)
return ""
}

return s.Name // userName
}


With the above code, I'm getting the following:

2023/07/21 18:11:00 net/http: invalid byte '\x7f' in Cookie.Value; dropping invalid bytes
2023/07/21 18:11:00 session raw &sessionNameTextA
{Name: Text:}
2023/07/21 18:11:00 unexpected EOF

The Cookie session is encoded with gob Encode. It should only contain plain text strings right? So where does the problem come from?

The whole program is at:

The recent change that got me into the problem is:

Please help. Thx.


Kurtis Rader

unread,
Jul 21, 2023, 6:40:33 PM7/21/23
to Tong Sun, golang-nuts
> The Cookie session is encoded with gob Encode. It should only contain plain text strings right?

No. Where did you get that idea? See https://pkg.go.dev/encoding/gob#hdr-Encoding_Details

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/13e154d0-d456-4e56-84f3-b28ad734d633n%40googlegroups.com.


--
Kurtis Rader
Caretaker of the exceptional canines Junior and Hank
Reply all
Reply to author
Forward
0 new messages