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

How Can I Correctly Set Cookies Using Go's net/http Package?

Barbara Streisand
Release: 2024-12-10 04:43:18
Original
769 people have browsed it

How Can I Correctly Set Cookies Using Go's net/http Package?

Setting Cookies with Net/HTTP from the Server

This article addresses the issue of setting cookies in Go using the net/http package. Upon encountering difficulties, you may have resorted to online searches but yielded unsatisfactory results.

Let's delve into the code 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{"test", "tcookie", "/", "www.domain.com", expire, expire.Format(time.UnixDate), 86400, true, true, "test=tcookie", []string{"test=tcookie"}}
    req.AddCookie(&cookie)
    io.WriteString(w, "Hello world!")
}

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

As highlighted in the response you received, you seem to be setting the cookie on the request rather than the response. For this purpose, net/http provides a method called SetCookie:

func SetCookie(w ResponseWriter, cookie *Cookie)
Copy after login

To set a cookie, you should use the SetCookie function as follows:

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, // duration in seconds.
        Secure:  true,
        HttpOnly: true,
    }
    http.SetCookie(w, &cookie)
    io.WriteString(w, "Hello world!")
}
Copy after login

By setting the cookie on the response, the browser will receive the cookie and store it accordingly. This will enable you to track user sessions and provide personalized experiences in your web application.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template