Golang net/http中Cookie的操做

net/http Cookie的使用方法:cookie

package main

import (
	"strings"
	"fmt"
	"io"
	"net/http"
)

//cookie設置方法一
func Cookie(w http.ResponseWriter,r *http.Request){
	ck:=&http.Cookie{
		Name:"myCookie",
		Value:"hello",
		Path:"/",
		Domain:"localhost",
		MaxAge:120,
	}

	http.SetCookie(w,ck)

	ck2,err:=r.Cookie("myCookie")

	if err!=nil{
		io.WriteString(w,err.Error())
		return
	}
	
	io.WriteString(w,ck2.Value)

}

//cookie設置方法二
func Cookie2(w http.ResponseWriter,r *http.Request){
	ck:=&http.Cookie{
		Name:"myCookie2",
		Value:"hello world",
		Path:"/",
		Domain:"localhost",
		MaxAge:120,
	}
	
	w.Header().Set("Set-Cookie",strings.Replace(ck.String()," ","%20",-1)) //http包中將空格視爲非法,因此須要在此處添加空格

	ck2,err:=r.Cookie("myCookie2")

	if err!=nil{
		io.WriteString(w,err.Error())
		return
	}

	io.WriteString(w,ck2.Value)
}

func main(){

	http.HandleFunc("/",Cookie)
	http.HandleFunc("/2",Cookie2)

	fmt.Println("listen......")
	
	http.ListenAndServe(":8081",nil)
}
相關文章
相關標籤/搜索