- Go Web Development Cookbook
- Arpit Aggarwal
- 431字
- 2021-08-27 19:01:21
How it works…
Once we run the program, the HTTP server will start listening locally 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:

Next, we will use this provided Cookie to access /home, as follows:
$ curl --cookie "session-name=MTUyMzEwMTI3NXxEdi1CQkFFQ180SUFBUkFCRUFBQUpmLUNBQUVHYzNSeWFXNW5EQThBRFdGMWRHaGxiblJwWTJGMFpXUUVZbTl2YkFJQ0FBRT18ou7Zxn3qSbqHHiajubn23Eiv8a348AhPl8RN3uTRM4M=;" http://localhost:8080/home
This results in the home page as a response from the server:

Let's understand the Go program we have written:
- Using var store *sessions.CookieStore, we declared a private cookie store to store sessions using secure cookies.
- Using func init() { store = sessions.NewCookieStore([]byte("secret-key")) }, we defined an init() function that runs before main() to create a new cookie store and assign it to the store.
- Next, we defined a home handler where we get a session from the cookie store for the given name after adding it to the registry using store.Get and fetch the value of the authenticated key from the cache. If it is true, then we write Home Page to an HTTP response stream; otherwise, we write a You are unauthorized to view the page. message along with a 403 HTTP code.
- Next, we defined a login handler where we again get a session, set the authenticated key with a value of true, save it, and finally write You have successfully logged in. to an HTTP response stream.
- Next, we defined a logout handler where we get a session, set an authenticated key with the value of false, save it, and finally write You have successfully logged out. to an HTTP response stream.
- Finally, we defined main() where we mapped all handlers, home, login, and logout, to /home, /login, and /logout respectively, and start the HTTP server on localhost:8080.
- 物聯網網絡安全及應用
- 社交電商運營策略、技巧與實操
- JBoss EAP6 High Availability
- 數字通信同步技術的MATLAB與FPGA實現:Altera/Verilog版(第2版)
- SSL VPN : Understanding, evaluating and planning secure, web/based remote access
- 數字調制解調技術的MATLAB與FPGA實現:Altera/Verilog版(第2版)
- CCNP TSHOOT(642-832)認證考試指南
- 6G新技術 新網絡 新通信
- IPv6網絡切片:使能千行百業新體驗
- SAE原理與網絡規劃
- Practical Web Penetration Testing
- Guide to NoSQL with Azure Cosmos DB
- 數字王國里的虛擬人:技術、商業與法律解讀
- 小型局域網組建
- 移動互聯網環境下的核心網剖析及演進