1

I have a situation where I want to read the contents of a cookie in Go. However the contents of the cookie is in a JSON format. (Changing the format of the cookie is not an option)

For example the contents of the cookie might be:

{"id":"abc","data":"information","on_off":false}

In JavaScript I'm easily able to read the contents of the cookie and parse it.

With Go, on the other hand, when I try to read the cookie with r.Cookie('my_cookie') I get the following error: http: named cookie not present.

If I modify the cookie to a simple string, then it works as expected.

Does anyone know what to do in this case? Is it just not possible to read a such a cookie in Go?

When I use r.Header.Get["Cookie"], the output it returns does contain the cookie and it's JSON value (listed among all the other cookies)

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
T. Short
  • 3,481
  • 14
  • 30
  • 1
    You cannot store JSON directly in a cookie value. Most of the characters used in JSON are not permitted in cookies. – Adrian Sep 24 '19 at 19:54
  • See related: https://stackoverflow.com/questions/1969232/allowed-characters-in-cookies – Adrian Sep 24 '19 at 19:55
  • Please, could you add the framework/library that you are using? Are you making a request or are you receiving request from a webserver? – alessiosavi Sep 24 '19 at 19:56
  • @alessiosavi - I'm receiving a request and it's a straight forward `go` set up importing `"net/url"` – T. Short Sep 24 '19 at 20:13
  • @CeriseLimón When I get the value of ` r.Header.Get["Cookie"]`. I can see the cookie (and it's value) in the output with all the other cookie data. – T. Short Sep 24 '19 at 20:21

1 Answers1

4

JSON uses many characters not permitted in HTTP cookie values per the RFC - for example, double quotes, commas, and whitespace characters are not permitted. The eastiest way to transfer JSON data via cookie would probably be to Base64 encode it when setting the cookie, and Base64 decode it when reading the cookie, using the encoding/base64 package.

Adrian
  • 42,911
  • 6
  • 107
  • 99
  • Thanks for your answer. If those characters are not permitted, how does the cookie even exist in the first place? – T. Short Sep 24 '19 at 20:11
  • 2
    That's a complicated question - not to be pedantic, but it depends on what you mean by "exist" here. A cookie is just a value passed back and forth in the Cookie and Set-Cookie headers. Only certain characters are permitted there. A client or server could send an invalid header (containing invalid characters), and the other side may or may not accept it. But according to the standard, JSON does not generally make for a valid cookie value. – Adrian Sep 24 '19 at 20:38