github.com/qiuhoude/go-web@v0.0.0-20220223060959-ab545e78f20d/prepare/05_session/cookie/main.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"net/http"
     7  )
     8  
     9  func main() {
    10  	http.HandleFunc("/setcookie", SetCookie)
    11  	http.HandleFunc("/getcookie", GetCookie)
    12  	http.ListenAndServe("localhost:8000", nil)
    13  }
    14  func SetCookie(w http.ResponseWriter, r *http.Request) {
    15  	//设置cookie
    16  	cookie := http.Cookie{Name: "name", Value: "hanru", Path: "/", Session: 5}
    17  	http.SetCookie(w, &cookie)
    18  	io.WriteString(w, "write cookie ok")
    19  
    20  }
    21  
    22  //Go读取cookie
    23  func GetCookie(w http.ResponseWriter, r *http.Request) {
    24  	cookie2, _ := r.Cookie("name")
    25  	fmt.Fprint(w, cookie2)
    26  	//还有另外一种读取方式
    27  	//for _, cookie := range r.Cookies() {
    28  	//	fmt.Fprint(w, cookie.Name)
    29  	//}
    30  }