官术网_书友最值得收藏!

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:

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:

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:

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:

Let's understand the changes we introduced in this recipe:

  1. Using var store *redisStore.RediStore, we declared a private RediStore to store sessions in Redis.
  2. 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.
  3. Finally, we updated main() to introduce the defer store.Close() statement, which closes the Redis store once we return from the function.
主站蜘蛛池模板: 荣成市| 西藏| 民权县| 怀远县| 荥阳市| 伊宁市| 讷河市| 安乡县| 怀化市| 贡嘎县| 天水市| 海林市| 汕尾市| 昌都县| 德令哈市| 镇江市| 中牟县| 克东县| 鸡泽县| 玉门市| 贵州省| 隆回县| 南汇区| 海伦市| 宁蒗| 广南县| 蒙阴县| 红桥区| 越西县| 扬中市| 镇康县| 开江县| 宝丰县| 镇远县| 汤原县| 花垣县| 牙克石市| 仪陇县| 贵南县| 林口县| 蓬莱市|