Home >Backend Development >Golang >How to Set Cookies Using Go's net/http Package?

How to Set Cookies Using Go's net/http Package?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-30 16:55:09889browse

How to Set Cookies Using Go's net/http Package?

Setting Cookies with net/http from the Server

In Go, using the net/http package to set cookies from the server involves storing the cookie information in the response sent to the client. Here's an improved version of the code snippet you provided:

package main

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

func indexHandler(w http.ResponseWriter, req *http.Request) {
    expire := time.Now().AddDate(0, 0, 1)
    cookie := &http.Cookie{
        Name:    "test",
        Value:   "tcookie",
        Path:    "/",
        Domain:  "www.domain.com",
        Expires: expire,
        MaxAge:  86400,
        Secure:  true,
        HttpOnly: true,
        SameSite: http.SameSiteLaxMode,
    }
    http.SetCookie(w, cookie)
    io.WriteString(w, "Hello world!")
}

func main() {
    http.HandleFunc("/", indexHandler)
    http.ListenAndServe(":80", nil)
}

This updated code sets the cookie on the response sent back to the client using the http.SetCookie function. The cookie parameters have also been adjusted to match the required structure. With this change, the code should correctly set a cookie with the specified attributes when the server responds to the client's request.

The above is the detailed content of How to Set Cookies Using Go's net/http Package?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn