• 接口文档
  • 使用示例

    接口文档

    https://godoc.org/github.com/gogf/gf/g/net/ghttp#Cookie

    任何时候都可以通过*ghttp.Request对象获取到当前请求对应的Cookie对象,因为Cookie和Session都是和请求会话相关,因此都属于ghttp.Request的成员对象,并对外公开。Cookie对象不需要手动Close,请求流程结束后,HTTP Server会自动关闭掉。

    此外,Cookie中封装了两个SessionId相关的方法,Cookie.SessionId()用于获取当前请求的SessionId,每个请求的SessionId都是唯一的,并且伴随整个请求流程。Cookie.SetSessionId(session string)用于自定义设置当前的SessionId,可以实现自定义的Session控制,以及Session跨域支持(特别是多服务器集群环境下)。

    在任何时候,我们都可以通过ghttp.Server对象来修改和获取Cookie的过期时间。

    使用示例

    1. package main
    2. import (
    3. "github.com/gogf/gf/g"
    4. "github.com/gogf/gf/g/os/gtime"
    5. "github.com/gogf/gf/g/net/ghttp"
    6. )
    7. func main() {
    8. s := g.Server()
    9. s.BindHandler("/cookie", func(r *ghttp.Request) {
    10. datetime := r.Cookie.Get("datetime")
    11. r.Cookie.Set("datetime", gtime.Datetime())
    12. r.Response.Write("datetime:", datetime)
    13. })
    14. s.SetPort(8199)
    15. s.Run()
    16. }

    执行外层的main.go,可以尝试刷新页面 http://127.0.0.1:8199/cookie ,显示的时间在一直变化。

    对于控制器对象而言,从基类控制器中继承了很多会话相关的对象指针,可以看做alias,可以直接使用,他们都是指向的同一个对象:

    1. type Controller struct {
    2. Request *ghttp.Request // 请求数据对象
    3. Response *ghttp.Response // 返回数据对象(r.Response)
    4. Server *ghttp.Server // Web Server对象(r.Server)
    5. Cookie *ghttp.Cookie // COOKIE操作对象(r.Cookie)
    6. Session *ghttp.Session // SESSION操作对象
    7. View *View // 视图对象
    8. }

    由于对于Web开发者来讲,Cookie都已经是非常熟悉的组件了,相关API也非常简单,这里便不再赘述。