Home >Backend Development >Golang >How to Correctly Set Cookies Using Go's net/http Package?
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.
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) }
In this example:
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!