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!