首页 > 解决方案 > k6环境变量导致GO错误“invalid character”

问题描述

k6 文档使使用环境变量变得非常简单,我尝试按照他们的说明进行操作,但是当我尝试运行它时出现 GO 错误:

ERRO[0000] GoError: parse https://${__ENV.TARGET_ENV}-api.mycompany.com/v1/managers/259999/properties": invalid character "{" in host name".

我在任何地方都看不到额外的支架。当我的网址为https://green-api.mycompany.com/v1/managers/259999/properties时,此脚本运行良好。我是否可能在某处缺少导入或依赖项?我要做的就是让它工作到当我键入 k6 run --env TARGET_ENV=green propertiesScript.js 时,它会针对http://green-api.mycompany.com/v1/managers/259999/properties执行。这是文件:

import { check } from "k6";

export let options = {
  thresholds: {
    http_req_duration: ["p(90)<300"], // 95% of requests should be below 200ms
    Errors: ["count<100"],
  },
};

export default function () {
  var url =
    "https://${__ENV.TARGET_ENV}-api.mycompany.com/v1/managers/259999/properties";

  const params = {
    headers: {
      "X-App-Token": "<our app token>",
      "X-Auth-Token":
        "<our auth token>",
      accept: "application/json",
    },
  };

  let res = http.get(url, params);
  console.log(res.body);
  console.log(JSON.stringify(res.headers));

  check(res, {
    "status is 200": (r) => r.status === 200,
  });
}

我还尝试添加场景并调整文件的正文。这些是场景:

  thresholds: {
    http_req_duration: ["p(90)<300"], // 95% of requests should be below 200ms
    Errors: ["count<100"],
  },
  scenarios: {
    pod_green: {
      tags: { my_custom_tag: "green" },
      env: { MYVAR: "green" },
      executor: "shared-iterations",
    },
    pod_red: {
      tags: { my_custom_tag: "red" },
      env: { MYVAR: "red" },
      executor: "shared-iterations",
    },
    staging: {
      tags: { my_custom_tag: "staging" },
      env: { MYVAR: "staging" },
      executor: "shared-iterations",
    },
  },
};

然后我编辑了我的导出默认函数,我能够让该脚本运行,但它运行在每一个环境中。

标签: k6

解决方案


url当您设置用于字符串插值的变量以在模板文字中工作时,您需要使用反引号。请参阅文档

所以在你的情况下,你应该有:

var url =
    `https://${__ENV.TARGET_ENV}-api.mycompany.com/v1/managers/259999/properties`;

推荐阅读