1 package main 2 3 import ( 4 "net/http" 5 "io" 6 ) 7 8 func main() { 9 http.HandleFunc("/", Cookie) 10 http.HandleFunc("/cookie1", Cookie1) 11 http.ListenAndServe(":8080", nil) 12 } 13 14 func Cookie(w http.ResponseWriter, r *http.Request) { 15 ck := &http.Cookie{ 16 Name: "myCookie", //名字 17 Value: "hello", //值 18 Path: "/", //路徑 19 Domain: "localhost", //域名 20 MaxAge: 120, //存活時間 21 } 22 23 http.SetCookie(w, ck) //設置cookie 24 25 ch2, err := r.Cookie("myCookie") 26 if err != nil { 27 io.WriteString(w, err.Error()) 28 return 29 } 30 io.WriteString(w, ch2.Value) 31 } 32 33 /** 34 當value為空格時 35 */ 36 func Cookie1(w http.ResponseWriter, r *http.Request) { 37 ck := &http.Cookie{ 38 Name: "myCookie", 39 Value: "hello World", 40 Path: "/", 41 Domain: "localhost", 42 MaxAge: 120, 43 } 44 45 w.Header().Set("set-cookie",ck.String()) 46 47 ch2, err := r.Cookie("myCookie") 48 if err != nil { 49 io.WriteString(w, err.Error()) 50 return 51 } 52 io.WriteString(w, ch2.Value) 53 }