golang封装cookie

JimPang · 2018-09-05 16:47:10 · 1099 次点击 · 预计阅读时间 2 分钟 · 大约8小时之前 开始浏览    
这是一个创建于 2018-09-05 16:47:10 的文章,其中的信息可能已经有所发展或是发生改变。

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

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

有疑问加站长微信联系(非本文作者))

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1099 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传