Go Web Application Cookie

スポンサーリンク

Read cookie from Http Request Header

Use request Header parameter or Cookie parameter

Example

func readCookies(w http.ResponseWriter, r *http.Request) {
	h := r.Header["Cookie"]
	fmt.Fprintln(w, h)
}

func readCookie2(w http.ResponseWriter, r *http.Request) {
	c1, err := r.Cookie("cookie1")
	if err != nil {
		fmt.Fprintln(w, "Cannot get cookie1")
	}
	cs := r.Cookies()
	fmt.Println(w, c1)
	fmt.Println(w, cs)
}

Write cookie (Set-Cookie Header)

Change Set-Cookie Header

Or, use cookie property

func setCookie1(w http.ResponseWriter, r *http.Request) {

	c1 := http.Cookie{
		Name:     "cookie1",
		Value:    "Go",
		HttpOnly: true,
	}

	c2 := http.Cookie{
		Name:     "cookie2",
		Value:    "Java",
		HttpOnly: true,
	}

	w.Header().Set("Set-Cookie", c1.String())
	w.Header().Add("Set-Cookie", c2.String())
}

func setCookie2(w http.ResponseWriter, r *http.Request) {
	c1 := http.Cookie{
		Name:     "cookie1",
		Value:    "Go",
		HttpOnly: true,
	}

	c2 := http.Cookie{
		Name:     "cookie2",
		Value:    "Java",
		HttpOnly: true,
	}
	http.SetCookie(w, &c1)
	http.SetCookie(w, &c2)
	/*
		rc := http.Cookie{
			Name:    "test",
			MaxAge:  -1,
			Expires: time.Unix(1, 0),
		}*/
}

未分類
スポンサーリンク
Professional Programmer2

コメント