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

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

Mary-Kate Olsen
Release: 2024-12-14 09:20:15
Original
316 people have browsed it

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

Setting Cookies with net/http from the Server

Setting cookies with Go's net/http package is accomplished through the SetCookie function. This is a common operation in web development and can be essential for tracking user sessions, preferences, and other information.

In your code sample, you are attempting to set a cookie on the request object (req.AddCookie). However, the proper way to set a cookie is to use the SetCookie function on the response object (w). This ensures that the cookie is sent as part of the HTTP response to the client.

The SetCookie function takes a single argument, which is a Cookie struct. This struct contains all the information necessary to create a cookie, including the name, value, path, domain, expiration time, and other attributes.

For example, the following code sets a cookie named "test" with a value of "tcookie" and an expiration time of one day:

cookie := &http.Cookie{
    Name:    "test",
    Value:   "tcookie",
    Expires: time.Now().Add(24 * time.Hour),
    Path:    "/",
}
http.SetCookie(w, cookie)
Copy after login

It's important to note that the SetCookie function will not automatically send the cookie to the client. The cookie will only be sent if the HTTP response includes the "Set-Cookie" header, which is automatically added by the http.ResponseWriter when a cookie is set using the SetCookie function.

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