When the HTTP client sends a request, it can customize the Header content sent to the server, a feature implemented using the SetHeader* related methods.

Method List:

  1. func (c *Client) SetHeader(key, value string) *Client
  2. func (c *Client) SetHeaderMap(m map[string]string) *Client
  3. func (c *Client) SetHeaderRaw(headers string) *Client

Let’s take a look at an example where the client customizes the sending of custom tracing information Span-Id and Trace-Id message headers using Header.

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.Writef(
  10. "Span-Id:%s,Trace-Id:%s",
  11. r.Header.Get("Span-Id"),
  12. r.Header.Get("Trace-Id"),
  13. )
  14. })
  15. s.SetPort(8199)
  16. s.Run()
  17. }

Since this is an example, the server logic is straightforward, directly returning the received Span-Id and Trace-Id parameters to the client.

Client

  1. Using the SetHeader 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.SetHeader("Span-Id", "0.0.1")
  10. c.SetHeader("Trace-Id", "NBC56410N97LJ016FQA")
  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 Header information using c.SetHeader.

  1. Using the SetHeaderRaw Method

This method is simpler and allows setting the client request Header via a raw Header string.

  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.SetHeaderRaw(`
  10. Referer: https://localhost
  11. Span-Id: 0.0.1
  12. Trace-Id: NBC56410N97LJ016FQA
  13. User-Agent: MyTestClient
  14. `)
  15. if r, e := c.Get(gctx.New(), "http://127.0.0.1:8199/"); e != nil {
  16. panic(e)
  17. } else {
  18. fmt.Println(r.ReadAllString())
  19. }
  20. }
  1. Execution Result

After executing the client code, the terminal will print the result returned by the server, as follows:

  1. Span-Id:0.0.1,Trace-Id:NBC56410N97LJ016FQA