Cookie与session是web开发常需要使用的玩意
先来个cookie的范例程序
package main
import (
"fmt"
"net/http"
)
func setCookie(w http.ResponseWriter, r *http.Request) {
c := http.Cookie{
Name: "username",
Value: "Tom",
HttpOnly: true,
}
http.SetCookie(w, &c)
}
func getCookie(w http.ResponseWriter, r *http.Request) {
c, err := r.Cookie("username")
if err != nil {
fmt.Fprintln(w, "Cannot get cookie")
}
fmt.Fprintln(w, c)
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "hello world")
}
func main() {
http.HandleFunc("/", indexHandler)
http.HandleFunc("/cookie/set", setCookie)
http.HandleFunc("/cookie/get", getCookie)
http.ListenAndServe("localhost:8000", nil)
}
范例中大致设定该cookie的name,所对应的value,以及设定HttpOnly,其实最好还是要设定其存活时间也会比较好
能设定的参数如下
type Cookie struct {
Name string
Value string
Path string // optional
Domain string // optional
Expires time.Time // optional
RawExpires string // for reading cookies only
// MaxAge=0 means no 'Max-Age' attribute specified.
// MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'
// MaxAge>0 means Max-Age attribute present and given in seconds
MaxAge int
Secure bool
HttpOnly bool
SameSite SameSite
Raw string
Unparsed []string // Raw text of unparsed attribute-value pairs
}
Name/Value: Cookie的名称和值
Path: 可以将Cookie限定在某个路径下,只有这个路径和它的子路径才可以访问。
Domain: 只关联的web服务器的Domain, 比如example.com。如果你设置的Cookie的domain为a.example.com,那麽访问b.example.com的时候是不能访问这个Cookie的。
Expires: 为Cookie过期时间,Cookie超过这个时间点就会被删除了。
RawExpires: Expires字串表示, 格式为Wdy, DD Mon YYYY HH:MM:SS或者Wdy, DD Mon YY HH:MM:SS
MaxAge: 最大存活时间。
Secure:设置 Cookie 只在HTTPS的请求中才会作用。
HttpOnly:跟安全性有关,建议true。
SameSite: 跟Chrome有关,主要是在处理跨域的安全问题。
备注:
这边要特别注意ListenAndServe的位置,如果在HandleFunc之前的话,会导致该路由吃不到唷,所以如果范例跑失败的话,建议注意一下这个部分
HttpOnly
这个部分是建议使用true,当 cookie 有设定 HttpOnly tue时,浏览器会限制 cookie 只能经由 HTTP(S) 协定来存取。因此当网站被 XSS 攻击时,我们有把 cookie HttpOnly设定为true,这样一来xss就无法直接透过 JavaScript 来盗取 cookie。
Session本来想一起拚完的,但真的累了~改天吧!!!!!
<<: Day2.程序运行的基本概念(预处理、编译、组译、链结)
Ubuntu - Ubuntu 查看 CPU 温度 参考资料 网址如下: How to Get CP...
在将主内存分配给操作系统中的进程时,有两个主要部分。 在连续内存分配中,进程被分配主内存的顺序块给整...
Positional Encoding 如果依照前面讲到的,self-attention只有vect...
哈罗~ 大家好,我是雪花冰 我是个从小喜欢玩电玩,立志长大要当 GM,却半路入坑程序这条不归路的攻城...
Aloha!我是少女人妻 Uerica!话说你们知道哈利波特的角色中谁最有主见吗~佛地魔!因为他不会...