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

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.
init() is always called, regardless of whether there's a main function or not, so if you import a package that has an init function, it will be executed .
  • 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.
主站蜘蛛池模板: 桂东县| 柳州市| 金湖县| 内乡县| 拜城县| 红原县| 开原市| 新化县| 翼城县| 张家港市| 格尔木市| 南靖县| 耒阳市| 济宁市| 临泉县| 惠水县| 大渡口区| 章丘市| 东平县| 阳原县| 文化| 临泽县| 陕西省| 连城县| 长春市| 永宁县| 西充县| 文山县| 九台市| 延安市| 枣庄市| 志丹县| 寿光市| 贵南县| 东乡县| 漳州市| 龙泉市| 凉城县| 米脂县| 周宁县| 云安县|