【go】 設置cookie的兩種方法


 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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM