When an HTTP client initiates a request, it can customize the Cookie content sent to the server. This feature is implemented using the SetCookie* related methods.

Method list:

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

Let’s look at an example of a client customizing Cookie.

Server

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/frame/g"
  4. "github.com/gogf/gf/v2/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. }

As this is an example, the server logic is straightforward, directly returning all received Cookie parameters to the client.

Client

  1. Using the SetCookie method
  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gogf/gf/v2/frame/g"
  5. "github.com/gogf/gf/v2/os/gctx"
  6. )
  7. func main() {
  8. c := g.Client()
  9. c.SetCookie("name", "john")
  10. c.SetCookie("score", "100")
  11. if r, e := c.Get(gctx.New(), "http://127.0.0.1:8199/"); e != nil {
  12. panic(e)
  13. } else {
  14. fmt.Println(r.ReadAllString())
  15. }
  16. }

Create a custom HTTP request client object using g.Client() and set custom Cookie using the c.SetCookie method. Here, we set two example Cookie parameters, one name, and one score.

  1. Using the SetCookieMap method

This method is simpler and allows setting Cookie key-value pairs in bulk.

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

After executing the client code, the terminal will print the server’s response as follows:

  1. map[name:john score:100]

As you can see, the server has received the custom Cookie parameters from the client.