【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