http only cookie

To create an HTTP-only cookie in Go, you can follow these steps:

  1. Import the necessary packages:
import (
    "net/http"
    "time"
)
  1. Create a new cookie using the http.Cookie struct:
cookie := &http.Cookie{
    Name:     "my_cookie",
    Value:    "cookie_value",
    Expires:  time.Now().Add(24 * time.Hour),
    HttpOnly: true,
}
  1. Set the cookie in the response headers:
http.SetCookie(w, cookie)

Here, w is the http.ResponseWriter object obtained as an argument in your handler function.

Let's go through each step in more detail:

Step 1: Import necessary packages

import (
    "net/http"
    "time"
)

In this step, we import the required packages for working with HTTP and handling time-related operations. The net/http package provides functions and types for building HTTP servers and clients, while the time package is used to deal with time-related operations.

Step 2: Create a new cookie

cookie := &http.Cookie{
    Name:     "my_cookie",
    Value:    "cookie_value",
    Expires:  time.Now().Add(24 * time.Hour),
    HttpOnly: true,
}

Here, we create a new cookie using the http.Cookie struct. We set the Name and Value fields to specify the name and value of the cookie, respectively. The Expires field is set to a time 24 hours from the current time using time.Now().Add(24 * time.Hour). This ensures that the cookie will be valid for 24 hours. Finally, we set the HttpOnly field to true to make the cookie accessible only through HTTP and not through client-side scripts.

Step 3: Set the cookie in the response headers

http.SetCookie(w, cookie)

In this step, we use the http.SetCookie function to set the cookie in the response header. The w parameter is the http.ResponseWriter object obtained as an argument in your handler function. This function adds the cookie to the response header, which will be sent back to the client.

By following these steps, you can create an HTTP-only cookie in Go.