登录
首页 >  Golang >  Go教程

如何使用 Golang 管理 HTTP cookie?

时间:2024-05-16 13:32:35 345浏览 收藏

Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《如何使用 Golang 管理 HTTP cookie?》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!


使用 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)
}

好了,本文到此结束,带大家了解了《如何使用 Golang 管理 HTTP cookie?》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>