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

方法列表:

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

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

服务端

  1. package main
  2. import (
  3. "github.com/gogf/gf/frame/g"
  4. "github.com/gogf/gf/net/ghttp"
  5. )
  6. func main() {
  7. s := g.Server()
  8. s.BindHandler("/", func(r *ghttp.Request){
  9. r.Response.Write(r.Cookie.Map())
  10. })
  11. s.SetPort(8199)
  12. s.Run()
  13. }

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

客户端

  1. 使用SetCookie方法

    ``` package main

  1. import (
  2. "fmt"
  3. "github.com/gogf/gf/frame/g"
  4. )
  5. func main() {
  6. c := g.Client()
  7. c.SetCookie("name", "john")
  8. c.SetCookie("score", "100")
  9. if r, e := c.Get("http://127.0.0.1:8199/"); e != nil {
  10. panic(e)
  11. } else {
  12. fmt.Println(r.ReadAllString())
  13. }
  14. }
  15. ```
  16. 通过`g.Client()`创建一个自定义的HTTP请求客户端对象,并通过`c.SetCookie`方法设置自定义的`Cookie`,这里我们设置了两个示例用的`Cookie`参数,一个`name`,一个`score`。
  1. 使用SetCookieMap方法

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

    ``` package main

  1. import (
  2. "fmt"
  3. "github.com/gogf/gf/frame/g"
  4. )
  5. func main() {
  6. c := g.Client()
  7. c.SetCookieMap(g.MapStrStr{
  8. "name": "john",
  9. "score": "100",
  10. })
  11. if r, e := c.Get("http://127.0.0.1:8199/"); e != nil {
  12. panic(e)
  13. } else {
  14. fmt.Println(r.ReadAllString())
  15. }
  16. }
  17. ```
  1. 执行结果

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

    1. map[name:john score:100]

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

Content Menu