Golang 操作Cookie

Golang 操作 Cookie

我们使用两种方法来 设置、读取 Cookie

示例

package main

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

// 访问:http://localhost:8888/
// 方法 1
func Cookie(w http.ResponseWriter, r *http.Request)  {
    // 浏览器中必须屏蔽 /favicon.ico
    if r.RequestURI == "/favicon.ico" {
        return
    }

    // 定义 Cookie
    ck := &http.Cookie{
        Name:   "myCookie",
        Value:  "hello",
        Path:   "/",
        Domain: "localhost",
        MaxAge: 120,
    }
    // 设置 Cookie
    http.SetCookie(w, ck)

    // 读取 Cookie
    ck2, err := r.Cookie("myCookie")
    if err != nil {
        io.WriteString(w, err.Error())
        return
    }
    // 向页面打印读取到的 Cookie
    io.WriteString(w, ck2.Value)
}

// 方法 2
// http://localhost:8888/cookie2
func Cookie2(w http.ResponseWriter, r *http.Request)  {
    // 浏览器中必须屏蔽 /favicon.ico
    if r.RequestURI == "/favicon.ico" {
        return
    }

    // 定义 Cookie
    ck := &http.Cookie{
        Name:   "myCookie",
        Value:  "Hello Cookie2",
        Path:   "/",
        Domain: "localhost",
        MaxAge: 120,
    }
    // 设置 Cookie
    // 必须将 Cookie.Value 中的空格替换掉
    w.Header().Set("Set-Cookie", strings.Replace(ck.String(), " ", "%", -1))

    // 读取 Cookie
    ck2, err := r.Cookie("myCookie")
    if err != nil {
        io.WriteString(w, err.Error())
        return
    }
    // 向页面打印读取到的 Cookie
    io.WriteString(w, ck2.Value)
}

func main()  {
    http.HandleFunc("/", Cookie)
    http.HandleFunc("/cookie2", Cookie2)

    http.ListenAndServe(":8888", nil)
}
讨论数量: 0

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!