Handling cookies
Cookies provide a way of easily storing data on the client side. This recipe illustrates how to set, retrieve and remove the cookies with the help of the standard library.
How to do it...
- Open the console and create the folder
chapter09/recipe10
. - Navigate to the directory.
- Create the file
cookies.go
with the following content:
package main import ( "fmt" "log" "net/http" "time" ) const cookieName = "X-Cookie" func main() { log.Println("Server is starting...") http.HandleFunc("/set", func(w http.ResponseWriter, r *http.Request) { c := &http.Cookie{ Name: cookieName, Value: "Go is awesome.", Expires: time.Now().Add(time.Hour), Domain: "localhost", } http.SetCookie(w, c) fmt.Fprintln(w, "Cookie is set!") }) http.HandleFunc("...