"' Gopackage libimport (" Net/http "" Time ")//used to make a cookie processing type cookiehandle struct {http_writer http. Responsewriter//used primarily to write head http_request *http. Request//is used primarily to obtain header information expires time. Duration//Expiration Time nanoseconds}//cookie initialize func cookieinit (w http.) Responsewriter, req *http. Request, expire string) *cookiehandle {//cookie Initialize Cookie: = new (Cookiehandle) cookie. Http_writer = Wcookie. Http_request = Reqcookie. Expires = cookie.expireduration (expire) return cookie}//get Cookiefunc (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 parse is valid time fails do not set valid time if err! = Nil {return 0}return expire_time}//set Cookiefunc (This *cookiehandle ) Setcookie (Key, Val string, expire ... string) {//Create Http.cookie pointer Cookie: = new (http. Cookie) Cookie. Name = Keycookie. Value = val//If there is a delivery timeout reset time-out time if Len (expire) > 0 {This. Expires = This.expireduration (expire[0])}//If you do not set the expiration time is not assigned if this. Expires! = 0 {cookie. Expires = time. Now (). ADD (this. Expires)}//call the HTTP packet to set the cookie is roughly the data generated by the cookie construct string header (). Set () HTTP. Setcookie (this. Http_writer, cookie)}//Delete cookiefunc (this *cookiehandle) Delcookie (key string) {cookie: = new (http. Cookie) Cookie. Name = key//The corresponding Cookiecookie can be emptied by changing the expiration time to -1 s. Expires = time. Now (). ADD (This.expireduration (" -1s")) http. Setcookie (this. Http_writer, Cookie)} Call code package Mainimport ("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") cookies. Setcookie ("Test", "Xiaochuan") W.write ([]byte (Cookie). GetCookie ("Test"))} It's a headache to write this thing. or too slag. 71 reads
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.