菜单
开源

Client

Client 是一个 HTTP 客户端构造函数,它会向其请求附加 baggage 头。使用 Client 类可以在 HTTP 请求中包含上下文,以便 Grafana pyroscope 可以纳入其结果。

Client 类可作为标准 http 模块的直接替代品,并会向请求附加 baggage 头。有关传播的详细信息,请参阅关于 baggage 头

Client 构造函数接受一个函数,该函数获取每个请求的方法、请求体和参数,并返回要添加到请求中的头映射。默认情况下,它会附加包含 Grafana Cloud Profiling 与 Grafana Cloud k6 集成所需信息的 baggage 头。

有关传播的详细信息,请参阅关于 baggage 头

示例

本示例演示了如何实例化客户端并使用它对 HTTP 调用进行插桩。本示例还说明了如何将客户端与标准 http 模块一起使用来执行非插桩的 HTTP 调用。

JavaScript
import { check } from 'k6';
import pyroscope from 'https://jslib.k6.io/http-instrumentation-pyroscope/1.0.2/index.js';
import http from 'k6/http';

// Explicitly instantiating a Pyroscope client allows to distinguish
// instrumented from non-instrumented HTTP calls, by keeping APIs separate.
const instrumentedHTTP = new pyroscope.Client();

const testData = { name: 'Bert' };

export default () => {
  // Using the pyroscope client instance, HTTP calls will have
  // baggage header added.
  let res = instrumentedHTTP.request('GET', 'http://httpbin.org/get', null, {
    headers: {
      'X-Example-Header': 'instrumented/request',
    },
  });

  // The client offers more flexibility over
  // the `instrumentHTTP` function, as it leaves the
  // imported standard `http` module untouched. Thus,
  // one can still perform non-instrumented HTTP calls
  // using it.
  res = http.post('http://httpbin.org/post', JSON.stringify(testData), {
    headers: { 'X-Example-Header': 'noninstrumented/post' },
  });

  res = instrumentedHTTP.del('http://httpbin.org/delete', null, {
    headers: { 'X-Example-Header': 'instrumented/delete' },
  });
};

HTTP 模块函数对应项

Client 类暴露了与标准 http 模块相同的 API,除了 Client 中没有 batch 方法。下表列出了在标准 http 模块中有对应项的 Client 方法

方法HTTP 对应项描述
Client.del(url, [body], [params])http.del执行插桩的 HTTP DELETE 请求。该方法具有与 http.del 函数相同的原型,并应透明地作为其直接替代品。
Client.get(url, [params])http.get执行插桩的 HTTP GET 请求。该方法具有与 http.get 函数相同的原型,并应透明地作为其直接替代品。
Client.head(url, [params])http.head执行插桩的 HTTP HEAD 请求。该方法具有与 http.head 函数相同的原型,并应透明地作为其直接替代品。
Client.options(url, [body], [params])http.options执行插桩的 HTTP OPTIONS 请求。该方法具有与 http.options 函数相同的原型,并应透明地作为其直接替代品。
Client.patch(url, [body], [params])http.patch执行插桩的 HTTP PATCH 请求。该方法具有与 http.patch 函数相同的原型,并应透明地作为其直接替代品。
Client.post(url, [body], [params])http.post执行插桩的 HTTP POST 请求。该方法具有与 http.post 函数相同的原型,并应透明地作为其直接替代品。
Client.put(url, [body], [params])http.put执行插桩的 HTTP PUT 请求。该方法具有与 http.put 函数相同的原型,并应透明地作为其直接替代品。
Client.request(method, url, [body], [params])http.request执行插桩的 HTTP 请求。该方法具有与 http.request 函数相同的原型,并应透明地作为其直接替代品。
Client.asyncRequest(method, url, [body], [params])http.asyncRequest执行插桩的 HTTP 异步请求。该方法具有与 http.asyncRequest 函数相同的原型,并应透明地作为其直接替代品。