How it works…

Once we run the program, the HTTP server will start locally listening on port 8080.

Browsing http://localhost:8080/read will display Hello in the browser, as you can see in the following screenshot:

Next, we will access http://localhost:8080/create, which will create a cookie with the name first-cookie and display the Cookie created message in the browser:

Now, subsequent access to http://localhost:8080/read will use first-cookie to display Hellofollowed by the value of first-cookie, as follows:

Let's understand the program we have written:

  • Using import ("fmt" "log" "net/http" "github.com/gorilla
    /securecookie")
    , we introduced an additional package—github.com/gorilla/securecookie, which we will use to encode and decode authenticated and encrypted cookie values.
  • Using var cookieHandler *securecookie.SecureCookie, we declared a private secure cookie.
  • Next, we updated the init() function to create SecureCookie passing a 64-byte hash key, which is used to authenticate values using HMAC and a 32-byte block key, which is used to encrypt values.
  • Next, we defined a createCookie handler where we create a Base64 encoded cookie with the key as username and the value as Foo using an Encode handler of gorilla/securecookie. Then, we add a Set-Cookie header to the provided ResponseWriter headers and write a Cookie created. message to an HTTP response.
  • Next, we defined a readCookie handler, where we retrieve a cookie from the request, which is first-cookie in our code, get a value for it, and write it to an HTTP response.
  • Finally, we defined main() where we mapped all handlers—createCookie and readCookie—to /create and /read respectively, and started the HTTP server on localhost:8080.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.4.181