You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 2 Next »

自定义Cookie

HTTP客户端发起请求时可以自定义发送给服务端的Cookie内容,该特性使用SetCookie*相关方法实现。

方法列表:

func (c *Client) SetCookie(key, value string) *Client
func (c *Client) SetCookieMap(m map[string]string) *Client

我们来看一个客户端自定义Cookie的示例。

服务端

package main

import (
    "github.com/gogf/gf/frame/g"
    "github.com/gogf/gf/net/ghttp"
)

func main() {
    s := g.Server()
    s.BindHandler("/", func(r *ghttp.Request){
        r.Response.Write(r.Cookie.Map())
    })
    s.SetPort(8199)
    s.Run()
}

由于是作为示例,服务端的逻辑很简单,直接将接收到的Cookie参数全部返回给客户端。

客户端

  1. 使用SetCookie方法

    package main
    
    
    import (
        "fmt"
        "github.com/gogf/gf/frame/g"
    )
    
    
    func main() {
        c := g.Client()
        c.SetCookie("name", "john")
        c.SetCookie("score", "100")
        if r, e := c.Get("http://127.0.0.1:8199/"); e != nil {
            panic(e)
        } else {
            fmt.Println(r.ReadAllString())
        }
    }
    

    通过g.Client()创建一个自定义的HTTP请求客户端对象,并通过c.SetCookie方法设置自定义的Cookie,这里我们设置了两个示例用的Cookie参数,一个name,一个score

  2. 使用SetCookieMap方法

    这个方法更加简单,可以批量设置Cookie键值对。

    package main
    
    
    import (
        "fmt"
        "github.com/gogf/gf/frame/g"
    )
    
    
    func main() {
        c := g.Client()
        c.SetCookieMap(g.MapStrStr{
            "name":  "john",
            "score": "100",
        })
        if r, e := c.Get("http://127.0.0.1:8199/"); e != nil {
            panic(e)
        } else {
            fmt.Println(r.ReadAllString())
        }
    }
    
  3. 执行结果

    客户端代码执行后,终端将会打印出服务端的返回结果,如下:

    map[name:john score:100]
    

    可以看到,服务端已经接收到了客户端自定义的Cookie参数。

  • No labels