package main import ( "net/http" "time" ) func main() { handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // create a new cookie with an expiration date of 1 hour from now expiration := time.Now().Add(1 * time.Hour) cookie := &http.Cookie{Name: "mycookie", Value: "foobar", Expires: expiration} // set the cookie in the response header http.SetCookie(w, cookie) }) http.ListenAndServe(":8080", handler) }
package main import ( "net/http" "time" ) func main() { handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // get the value of the "mycookie" cookie cookie, err := r.Cookie("mycookie") if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // check if the cookie has expired if time.Now().After(cookie.Expires) { http.Error(w, "Cookie has expired", http.StatusUnauthorized) return } // send a success response w.Write([]byte("Welcome back!")) }) http.ListenAndServe(":8080", handler) }In this example, the value of the "mycookie" cookie is retrieved from the HTTP request. Then, the expiration date of the cookie is checked to see if it has expired. If the cookie has expired, an error response is sent back to the client. Otherwise, a success response is sent. In conclusion, the net/http package is the package library used to manage HTTP clients and servers in Go. It includes support for cookies as an HTTP-specific feature. The Expires attribute of a cookie can be used to determine how long the cookie remains valid.