卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章64336本站已运行4115

如何使用 Golang 管理 HTTP cookie?

使用 golang 管理 http cookie 的方法有:设置 cookie:使用 http.cookie 设置其名称、值、过期时间、域、路径、安全标志和 httponly 标志,然后使用 http.setcookie() 添加到响应头上。获取 cookie:使用 r.cookie() 来获取特定名称的 cookie,然后可以使用它的 value 字段访问其值。删除 cookie:获取 cookie 后,将其 expires 字段设置为过去的时间,并将其添加到响应头上,这会将 cookie 从客户端浏览器中删除。

如何使用 Golang 管理 HTTP cookie?

如何使用 Golang 管理 HTTP Cookie?

在 Golang 中管理 HTTP cookie 的常见方法是使用 net/http 包提供的 API。以下是如何设置、获取和删除 HTTP cookie 的步骤:

设置 Cookie

package main

import (
    "fmt"
    "net/http"
    "time"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        // 设置名为 "session_id" 的 cookie,并将它的值设置为 "some-uuid"
        cookie := &http.Cookie{
            Name: "session_id",
            Value: "some-uuid",
        }
        // 设置 cookie 的过期时间
        cookie.Expires = time.Now().Add(24 * time.Hour)
        // 设置 cookie 的域(默认为当前请求的域)
        cookie.Domain = "example.com"
        // 设置 cookie 的路径(默认为 "/")
        cookie.Path = "/"
        // 设置 cookie 的安全标志(默认为 false)
        cookie.Secure = true
        // 设置 cookie 的 HttpOnly 标志(默认为 false)
        cookie.HttpOnly = true

        // 将 cookie 添加到响应头上
        http.SetCookie(w, cookie)
        fmt.Fprint(w, "Cookie set successfully")
    })

    http.ListenAndServe(":8080", nil)
}

获取 Cookie

package main

import (
    "fmt"
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        // 获取名为 "session_id" 的 cookie
        cookie, err := r.Cookie("session_id")
        if err != nil {
            fmt.Fprint(w, "Cookie not found")
            return
        }

        // 打印 cookie 的值
        fmt.Fprint(w, "Cookie value:", cookie.Value)
    })

    http.ListenAndServe(":8080", nil)
}

删除 Cookie

package main

import (
    "fmt"
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        // 获取名为 "session_id" 的 cookie
        cookie, err := r.Cookie("session_id")
        if err != nil {
            fmt.Fprint(w, "Cookie not found")
            return
        }

        // 设置 cookie 的过期时间为过去,从而删除它
        cookie.Expires = time.Now().Add(-1 * time.Second)

        // 将 cookie 添加到响应头上
        http.SetCookie(w, cookie)
        fmt.Fprint(w, "Cookie deleted successfully")
    })

    http.ListenAndServe(":8080", nil)
}
卓越飞翔博客
上一篇: c#用什么软件
下一篇: c#和c++有什么区别
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏