DEV Community

Ega Prasetya
Ega Prasetya

Posted on

Golang Web - HTTP Cookie

Cookie is a small data piece of data stored on the users computer by the web browser while browsing a website. So in this chapter we will learn how to create and access cookie in Go, so let`s do it.

PRACTICE

Create file main.go and registration two route.

Alt Text

The variable cookieName contains a string, it later on for using as a name cookie.

  • Route / work as to create new cookie
  • Route /delete have a work for to delete cookie and then redirect to route / until new cookie created.

Ok, so now create function handler ActionIndex(), in this function the data is a string random to save in the cookie.

Alt Text

The cookie can be access from method .cookie() belong objek *http.Request. This method return two informations.

  • Objec Cookie
  • Error, if have

Ok, so next create function handler ActionDelete(), this handler for deleted cookie with name cookieName and redirect to route / to create a new cookie.

Alt Text

TESTING

Run this program and see the result

Alt Text

Finally! Hope your enjoy it.

Top comments (0)