您的位置:首页 > 编程语言 > Go语言

【寒江雪】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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: