golang web cookie 封装调用

 http cookie 主要是用的内置包中的cookie 进行设置以及 获取的

一开始准备自己写 调用 http.ResponseWriter header().set  直接这么搞

后面发现 如果我这边需要设置 超时时间的话这就玩不了

最后 拿 http.cookie 搞完才发现这个 时间格式 是 GMT 时间格式。处处是坑到处踩

附上渣代码。

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")))
}

写个这玩意也是头痛万分啊。还是太渣

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一名路过的小码农

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值