Techieindoor

Go – HTTP SetCookie Function in Go

In this article, we will explore the http SetCookie function in Go net/http package in detail, along with examples.

Introduction:

In Go, the net/http package provides an easy-to-use interface to interact with HTTP requests and responses. One important aspect of HTTP is the ability to set and manage cookies. The http.SetCookie function allows developers to set cookies in HTTP responses, which can then be used for various purposes, such as authentication, personalization, and maintaining user sessions.

Overview of the http.SetCookie Function

Syntax:

func SetCookie(w ResponseWriter, cookie *Cookie)

The function takes two arguments:

The http.Cookie struct has several fields that you can use to configure the cookie:

type Cookie struct {
    Name       string
    Value      string
    Path       string
    Domain     string
    Expires    time.Time
    RawExpires string
    MaxAge     int
    Secure     bool
    HttpOnly   bool
    SameSite   SameSite
    Raw        string
    Unparsed   []string
}

Now, let’s explore how to use the http.SetCookie function with a practical example.

Example: Setting a Cookie in a Go Web Application

In this example, we’ll create a simple web application that uses the http.SetCookie function to set a cookie with a personalized welcome message.

package main

import (
    "fmt"
    "net/http"
    "time"
)

func setCookieHandler(w http.ResponseWriter, r *http.Request) {
    // Create a new cookie
    cookie := &http.Cookie{
        Name:     "welcomeMessage",
        Value:    "Hello, Gopher!",
        Path:     "/",
        Expires:  time.Now().Add(24 * time.Hour),
        HttpOnly: true,
    }

    // Set the cookie using the http.SetCookie function
    http.SetCookie(w, cookie)

    // Respond to the client
    fmt.Fprint(w, "Cookie has been set!")
}

func main() {
    // Register the setCookieHandler function for the "/set-cookie" route
    http.HandleFunc("/set-cookie", setCookieHandler)

    // Start the web server
    fmt.Println("Starting server on :8080...")
    http.ListenAndServe(":8080", nil)
}

To test the application, run the program and visit http://localhost:8080/set-cookie in your web browser. The server will set a cookie named “welcomeMessage” with the value “Hello, Gopher!”.

Conclusion

The http.SetCookie function in Go is a powerful tool for setting cookies in HTTP responses, enabling you to manage user sessions, implement authentication, and personalize your web applications. The example provided in this article demonstrates the basics of setting a cookie, but remember that you can further customize the cookie by modifying the http.Cookie struct fields as needed.

To check more Go related articles. Pls click given below link:

Golang tutorial

https://www.techieindoor.com/category/leetcode/

Exit mobile version