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

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

Susan Sarandon
Release: 2024-12-21 05:50:12
Original
330 people have browsed it

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

Setting Cookies with Go's net/http from the Server

Setting cookies with Go's net/http package can be a straightforward task. However, a common pitfall is attempting to set cookies on the request object, rather than the response.

Implementation

Here's how you can correctly set a cookie using net/http:

package main

import (
    "fmt"
    "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,
        RawExpires:  expire.Format(time.UnixDate),
        MaxAge:     86400,
        Secure:     true,
        HttpOnly:   true,
        SameSite:    http.SameSiteStrictMode,
        Raw:          "test=tcookie",
        Unparsed: []string{"test=tcookie"},
    }

    http.SetCookie(w, cookie) // Set the cookie on the response
    fmt.Fprint(w, "Hello world!")
}

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

Explanation

In this example:

  • http.SetCookie(w, cookie) is used to add the cookie to the response.
  • The cookie is configured with various attributes, such as name, value, path, domain, expiration, and security settings.
  • fmt.Fprint(w, "Hello world!") sends the response to the client, including the set cookie.

The above is the detailed content of How to 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