【寒江雪】Go-Web-setCookie
2018-01-25 21:05
295 查看
Go-Web-setCookie
使用go语言的net/http包写Web服务,需要在返回的响应头部中写入cookie的时候,可以通过ResponseWriter接口写入。Cookie是一个专门的结构,详情如下:
// A Cookie represents an HTTP cookie as sent in the Set-Cookie header of an // HTTP response or the Cookie header of an HTTP request. // // See http://tools.ietf.org/html/rfc6265 for details. 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 Raw string Unparsed []string // Raw text of unparsed attribute-value pairs }
Name和Value将会是一个键值对,Expires和MaxAge是Cookie的过期时间。下面这段代码就是用来设置Cookie的,并且在访问/hello的时候会将客户端发来的Cookie打印出来,当Cookie过期之后,会显示找不到Cookie.
package main import ( "net/http" "fmt" "runtime" "reflect" "time" "log" ) func logName(h http.HandlerFunc)http.HandlerFunc{ return func(w http.ResponseWriter,r *http.Request){ name := runtime.FuncForPC(reflect.ValueOf(h).Pointer()).Name() fmt.Println("Handler function called - " + name) h(w,r) } } func hello(w http.ResponseWriter,r *http.Request){ fmt.Fprint(w,"Hello World") } func sho 4000 wCookie(h http.HandlerFunc)http.HandlerFunc{ return func(w http.ResponseWriter,r *http.Request){ log.Println(r.Cookie("cookie")) h(w,r) } } func setCookie(w http.ResponseWriter,r *http.Request){ cookie := http.Cookie{ Name:"cookie", Value:r.Host, Expires:time.Now().Add(time.Minute), } http.SetCookie(w,&cookie) } func main(){ server := http.Server{ Addr:"127.0.0.1:10010", } http.HandleFunc("/helllo",logName(showCookie(hello))) http.HandleFunc("/setCookie",setCookie) server.ListenAndServe() }
下面是调试的信息
2018/01/25 20:50:39 cookie=127.0.0.1:10010 <nil> Handler function called - main.showCookie.func1 Handler function called - main.showCookie.func1 2018/01/25 20:51:41 http: named cookie not present
相关文章推荐
- go web 第二天 学习笔记
- GO搭建一个web服务器
- Go Web开发之Revel - 测试
- Go语言Web框架gwk介绍 (一)
- 一个不错的Go语言实现的web框架
- 基于 Web 的 Go 语言 IDE - Wide 1.5.2 发布!
- go web: 2 封装日志包log
- 基于 Web 的 Go 语言 IDE - Wide 1.2.0 发布!
- 关于webconsole报../website/console.go:35: undefined: ssh.InsecureIgnoreHostkey 错误解决方案
- 使用 Go 和 WebSockets 构建实时聊天服务器
- 【Go web开发之revel+mgo】第6章 实现留言板功能
- 最好的6个Go语言Web框架
- 最好的6个Go语言Web框架
- go get code.google.com/p/go.net/websocket失败
- IBM的云平台Bluemix使用初体验——创建Go语言 Web 应用程序,添加并使用语言翻译服务
- golang实战使用gin+xorm搭建go语言web框架restgo详解6.1 模型M和Orm
- Sites to go if you want to learn web development
- 基于 Web 的 Go 语言 IDE - Wide 1.4.0 发布!
- 利用supervisor在linux上部署goweb项目
- GoWeb template.ParseFiles页面空白解析