```go
package lib
import (
"net/http"
"time"
)
//用来做cookie 处理
type CookieHandle struct {
Http_writer http.ResponseWriter //主要用来写入头部
Http_request *http.Request //主要用来获取头部信息
Expires time.Duration //过期时间 纳秒
}
//cookie 初始化
func CookieInit(w http.ResponseWriter, req *http.Request, expire string) *CookieHandle {
//cookie 初始化
cookie := new(CookieHandle)
cookie.Http_writer = w
cookie.Http_request = req
cookie.Expires = cookie.expireDuration(expire)
return cookie
}
//获取cookie
func (this *CookieHandle) GetCookie(key string) string {
cookie, cookie_err := this.Http_request.Cookie(key)
if cookie_err != nil {
return ""
}
return cookie.Value
}
func (this *CookieHandle) expireDuration(expire string) time.Duration {
expire_time, err := time.ParseDuration(expire)
//如果解析有效时时间失败 不设置有效时间
if err != nil {
return 0
}
return expire_time
}
//设置cookie
func (this *CookieHandle) SetCookie(key, val string, expire ...string) {
//创建 http.cookie 指针
cookie := new(http.Cookie)
cookie.Name = key
cookie.Value = val
//如果有传递超时时间 重新设置超时时间
if len(expire) > 0 {
this.Expires = this.expireDuration(expire[0])
}
//如果不设置 过期时间 不赋值
if this.Expires != 0 {
cookie.Expires = time.Now().Add(this.Expires)
}
//调用http 包 进行设置cookie 大致是 讲cookie 构造体的数据 生成 string header().set()
http.SetCookie(this.Http_writer, cookie)
}
//删除cookie
func (this *CookieHandle) DelCookie(key string) {
cookie := new(http.Cookie)
cookie.Name = key
//讲过期时间改为 -1 s 就可以清空对应的cookie
cookie.Expires = time.Now().Add(this.expireDuration("-1s"))
http.SetCookie(this.Http_writer, cookie)
}
调用代码
package main
import (
"bbs/lib"
"net/http"
)
func main() {
http.HandleFunc("/", test)
http.ListenAndServe(":8080", nil)
}
func test(w http.ResponseWriter, req *http.Request) {
cookie := lib.CookieInit(w, req, "1m")
cookie.SetCookie("test", "xiaochuan")
w.Write([]byte(cookie.GetCookie("test")))
}
写个这玩意也是头痛万分啊。还是太渣
```
有疑问加站长微信联系(非本文作者))