Since gclient.Client internally wraps and extends the http.Client object from the standard library, any features available in http.Client are also supported by gclient.Client. Here, we are discussing examples of Transport usage. Let’s look at a few examples:

Using Unix Socket

The client and server communicate using Unix Socket, implemented using Transport. The following code is excerpts from a real project and cannot run independently, only for reference.

  1. func (*Guardian) ConvertContainerPathToHostPath(
  2. ctx context.Context, namespace, podName, containerName, containerPath string,
  3. ) (string, error) {
  4. var (
  5. client = g.Client()
  6. url = "http://localhost/api/v1/pod/path"
  7. req = webservice.HostPathInfoReq{
  8. Namespace: namespace,
  9. PodName: podName,
  10. ContainerName: containerName,
  11. ContainerPath: containerPath,
  12. }
  13. res *webservice.HostPathInfoRes
  14. )
  15. client.Transport = &http.Transport{
  16. DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
  17. return net.Dial("unix", serviceSocketPath)
  18. },
  19. }
  20. err := client.ContentJson().GetVar(ctx, url, req).Scan(&res)
  21. if err != nil {
  22. return "", gerror.Wrapf(
  23. err,
  24. `request guardian failed for url: %s, req: %s`,
  25. url, gjson.MustEncodeString(req),
  26. )
  27. }
  28. if res == nil {
  29. return "", gerror.Newf(
  30. `nil response from guardian request url: %s, req: %s`,
  31. url, gjson.MustEncodeString(req),
  32. )
  33. }
  34. return res.HostPath, nil
  35. }

Setting Client Connection Pool Size Parameters

  1. func ExampleNew_MultiConn_Recommend() {
  2. var (
  3. ctx = gctx.New()
  4. client = g.Client()
  5. )
  6. // controls the maximum idle (keep-alive) connections to keep per-host
  7. client.Transport.(*http.Transport).MaxIdleConnsPerHost = 5
  8. for i := 0; i < 5; i++ {
  9. go func() {
  10. if r, err := client.Get(ctx, "http://127.0.0.1:8999/var/json"); err != nil {
  11. panic(err)
  12. } else {
  13. fmt.Println(r.ReadAllString())
  14. r.Close()
  15. }
  16. }()
  17. }
  18. time.Sleep(time.Second * 1)
  19. // Output:
  20. //{"id":1,"name":"john"}
  21. //{"id":1,"name":"john"}
  22. //{"id":1,"name":"john"}
  23. //{"id":1,"name":"john"}
  24. //{"id":1,"name":"john"}
  25. }