![Go Web Development Cookbook](https://wfqqreader-1252317822.image.myqcloud.com/cover/993/36699993/b_36699993.jpg)
How it works…
Once we run the program, the HTTP server will start locally listening on port 8080.
Next, we will execute a couple of commands to see how the session works.
First, we will access /home by executing the following command:
$ curl -X GET http://localhost:8080/home
This will result in an unauthorized access message from the server as shown in the following screenshot:
![](https://epubservercos.yuewen.com/DEF31F/19470394801573606/epubprivate/OEBPS/Images/060b9289-61e3-4786-bab8-6be435d42f95.png?sign=1738852399-7fPzNK96IRXvPzD7U3tbxrSC4U1qv0dO-0-61b06aaad08f1afa572b7c76c4ba99a2)
This is because we first have to log in to an application, which will create a session ID that the server will validate before providing access to any web page. So, let's log in to the application:
$ curl -X GET -i http://localhost:8080/login
Executing the previous command will give us the Cookie, which has to be set as a request header to access any web page:
![](https://epubservercos.yuewen.com/DEF31F/19470394801573606/epubprivate/OEBPS/Images/75be8a84-1ba2-404b-abb1-3c64d109b0ad.png?sign=1738852399-5QXKTMDHsY6mv2V2F186GsWoIP3jsYpq-0-b65647f4f31e1a8c982b4bcb198d5451)
Once the previous command is executed, a Cookie will be created and saved in Redis, which you can see by executing the command from redis-cli or in the Redis Browser, as shown in the following screenshot:
![](https://epubservercos.yuewen.com/DEF31F/19470394801573606/epubprivate/OEBPS/Images/13be0e7f-26c1-42c3-94db-70ae68aa1b54.png?sign=1738852399-3oR6GV7yyfK56ygoV4muqAzhzygGgJv6-0-5633b14cd1f1ca2b87f2dabab0db5322)
Next, we will use the Cookie provided to access /home, as follows:
$ curl --cookie "session-name=MTUyMzEwNDUyM3xOd3dBTkV4T1JrdzNURFkyUkVWWlQxWklUekpKVUVOWE1saFRUMHBHVTB4T1RGVXlSRU5RVkZWWk5VeFNWVmRPVVZSQk4wTk1RMUU9fAlGgLGU-OHxoP78xzEHMoiuY0Q4rrbsXfajSS6HiJAm;" http://localhost:8080/home
This results in the Home Page as a response from the server:
![](https://epubservercos.yuewen.com/DEF31F/19470394801573606/epubprivate/OEBPS/Images/d723b277-e3d6-463e-95f9-6c8ca2e20624.png?sign=1738852399-4k3bKEHXne5x7qwgVitcruaowo1XvpLH-0-a43fd004c0613ecba9790d8163003664)
Let's understand the changes we introduced in this recipe:
- Using var store *redisStore.RediStore, we declared a private RediStore to store sessions in Redis.
- Next, we updated the init() function to create NewRediStore with a size and maximum number of idle connections as 10, and assigned it to the store. If there is an error while creating a store, then we log the error and exit with a status code of 1.
- Finally, we updated main() to introduce the defer store.Close() statement, which closes the Redis store once we return from the function.