由于gclient.Client内部封装扩展于标准库的http.Client对象,因此标准库http.Client有的特性,gclient.Client也是支持的。我们这里提到的例子是Transport使用。来看几个示例:

使用Unix Socket

客户端和服务端使用Unix Socket通信,使用Transport来实现。以下代码为真实项目代码摘选,无法独立运行,仅做参考。

  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. }

设置客户端连接池大小参数

  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. }