[
  {
    "path": ".github/workflows/go.yml",
    "content": "# This workflow will build a golang project\n# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-go\n\nname: Go\n\non:\n  push:\n    branches: [ \"master\" ]\n  pull_request:\n    branches: [ \"master\" ]\n\njobs:\n\n  build:\n    runs-on: ubuntu-latest\n    steps:\n    - uses: actions/checkout@v4\n\n    - name: Set up Go\n      uses: actions/setup-go@v4\n      with:\n        go-version: '1.21'\n\n    - name: Build\n      run: go build -v ./...\n\n    - name: Test\n      run: go test -v ./...\n"
  },
  {
    "path": ".gitignore",
    "content": "bin/"
  },
  {
    "path": ".travis.yml",
    "content": "dist: bionic\nlanguage: go\ngo:\n  - \"1.13\"\n"
  },
  {
    "path": "Dockerfile",
    "content": "FROM golang:1.15 as build\n\n# Create appuser.\n# See https://stackoverflow.com/a/55757473/12429735\nENV USER=appuser\nENV UID=10001\nRUN adduser \\\n    --disabled-password \\\n    --gecos \"\" \\\n    --home \"/nonexistent\" \\\n    --shell \"/sbin/nologin\" \\\n    --no-create-home \\\n    --uid \"${UID}\" \\\n    \"${USER}\"\n\nRUN apt-get update && apt-get install -y ca-certificates\nRUN go get github.com/rakyll/hey\n\n# Build\nWORKDIR /go/src/github.com/rakyll/hey\nRUN go mod download\nRUN CGO_ENABLED=0 GOOS=linux go build -o /go/bin/hey hey.go\n\n###############################################################################\n# final stage\nFROM scratch\nCOPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/\nCOPY --from=build /etc/passwd /etc/passwd\nCOPY --from=build /etc/group /etc/group\nUSER appuser:appuser\n\nARG APPLICATION=\"hey\"\nARG DESCRIPTION=\"HTTP load generator, ApacheBench (ab) replacement, formerly known as rakyll/boom\"\nARG PACKAGE=\"rakyll/hey\"\n\nLABEL org.opencontainers.image.ref.name=\"${PACKAGE}\" \\\n    org.opencontainers.image.authors=\"Jaana Dogan <@rakyll>\" \\\n    org.opencontainers.image.documentation=\"https://github.com/${PACKAGE}/README.md\" \\\n    org.opencontainers.image.description=\"${DESCRIPTION}\" \\\n    org.opencontainers.image.licenses=\"Apache 2.0\" \\\n    org.opencontainers.image.source=\"https://github.com/${PACKAGE}\"\n\nCOPY --from=build /go/bin/${APPLICATION} /hey\nENTRYPOINT [\"/hey\"]\n"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"{}\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright {yyyy} {name of copyright owner}\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n   "
  },
  {
    "path": "Makefile",
    "content": "binary = hey\n\nrelease:\n\tGOOS=windows GOARCH=amd64 go build -o ./bin/$(binary)_windows_amd64\n\tGOOS=linux GOARCH=amd64 go build -o ./bin/$(binary)_linux_amd64\n\tGOOS=darwin GOARCH=amd64 go build -o ./bin/$(binary)_darwin_amd64\n\nupload:\n\tgsutil -m cp -r ./bin/* gs://hey-releases/\n\nrelease-upload: release upload\n\n"
  },
  {
    "path": "README.md",
    "content": "![hey](http://i.imgur.com/szzD9q0.png)\n\nhey is a tiny program that sends some load to a web application.\n\nhey was originally called boom and was influenced from Tarek Ziade's\ntool at [tarekziade/boom](https://github.com/tarekziade/boom). Using the same name was a mistake as it resulted in cases\nwhere binary name conflicts created confusion.\nTo preserve the name for its original owner, we renamed this project to hey.\n\n## Installation\n\n  - Linux (amd64): https://storage.googleapis.com/hey-releases/hey_linux_amd64\n  - macOS (amd64): https://storage.googleapis.com/hey-releases/hey_darwin_amd64\n  - Windows (amd64): https://storage.googleapis.com/hey-releases/hey_windows_amd64\n\n### Package Managers\n\nmacOS:\n-  [Homebrew](https://brew.sh/) users can use `brew install hey`.\n\n## Usage\n\nhey runs provided number of requests in the provided concurrency level and prints stats.\n\nIt also supports HTTP2 endpoints.\n\n```\nUsage: hey [options...] <url>\n\nOptions:\n  -n  Number of requests to run. Default is 200.\n  -c  Number of workers to run concurrently. Total number of requests cannot\n      be smaller than the concurrency level. Default is 50.\n  -q  Rate limit, in queries per second (QPS) per worker. Default is no rate limit.\n  -z  Duration of application to send requests. When duration is reached,\n      application stops and exits. If duration is specified, n is ignored.\n      Examples: -z 10s -z 3m.\n  -o  Output type. If none provided, a summary is printed.\n      \"csv\" is the only supported alternative. Dumps the response\n      metrics in comma-separated values format.\n\n  -m  HTTP method, one of GET, POST, PUT, DELETE, HEAD, OPTIONS.\n  -H  Custom HTTP header. You can specify as many as needed by repeating the flag.\n      For example, -H \"Accept: text/html\" -H \"Content-Type: application/xml\" .\n  -t  Timeout for each request in seconds. Default is 20, use 0 for infinite.\n  -A  HTTP Accept header.\n  -d  HTTP request body.\n  -D  HTTP request body from file. For example, /home/user/file.txt or ./file.txt.\n  -T  Content-type, defaults to \"text/html\".\n  -a  Basic authentication, username:password.\n  -x  HTTP Proxy address as host:port.\n  -h2 Enable HTTP/2.\n\n  -host\tHTTP Host header.\n\n  -disable-compression  Disable compression.\n  -disable-keepalive    Disable keep-alive, prevents re-use of TCP\n                        connections between different HTTP requests.\n  -disable-redirects    Disable following of HTTP redirects\n  -cpus                 Number of used cpu cores.\n                        (default for current machine is 8 cores)\n```\n\n## Examples\n\nMake requests with default settings:\n```\nhey https://google.com\n```\n\nMake 1000 requests with 100 concurrent workers:\n```\nhey -n 1000 -c 100 https://google.com\n```\n\nRun load test for 30 seconds:\n```\nhey -z 30s https://google.com\n```\n\nMake POST request with custom body:\n```\nhey \\\n    -m POST \\\n    -d \"param1=value1&param2=value2\" \\\n    https://google.com\n```\n\nAdd custom headers:\n```\nhey \\\n    -H \"Accept: application/json\" \\\n    -H \"Authorization: Bearer token\" \\\n    https://google.com\n```\n\nTest with HTTP/2:\n```\nhey -h2 https://google.com\n```\n\nRate limit to 10 queries per second per worker:\n```\nhey -q 10 -c 5 -z 30s https://google.com\n```\n"
  },
  {
    "path": "go.mod",
    "content": "module github.com/rakyll/hey\n\nrequire golang.org/x/net v0.48.0\n\nrequire golang.org/x/text v0.33.0 // indirect\n\ngo 1.24.0\n"
  },
  {
    "path": "go.sum",
    "content": "golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=\ngolang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=\ngolang.org/x/text v0.33.0 h1:B3njUFyqtHDUI5jMn1YIr5B0IE2U0qck04r6d4KPAxE=\ngolang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8=\n"
  },
  {
    "path": "hey.go",
    "content": "// Copyright 2014 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n// Command hey is an HTTP load generator.\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"math\"\n\t\"net/http\"\n\tgourl \"net/url\"\n\t\"os\"\n\t\"os/signal\"\n\t\"regexp\"\n\t\"runtime\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/rakyll/hey/requester\"\n)\n\nconst (\n\theaderRegexp = `^([\\w-]+):\\s*(.+)`\n\tauthRegexp   = `^(.+):([^\\s].+)`\n\theyUA        = \"hey/0.0.1\"\n)\n\nvar (\n\tm           = flag.String(\"m\", \"GET\", \"\")\n\theaders     = flag.String(\"h\", \"\", \"\")\n\tbody        = flag.String(\"d\", \"\", \"\")\n\tbodyFile    = flag.String(\"D\", \"\", \"\")\n\taccept      = flag.String(\"A\", \"\", \"\")\n\tcontentType = flag.String(\"T\", \"text/html\", \"\")\n\tauthHeader  = flag.String(\"a\", \"\", \"\")\n\thostHeader  = flag.String(\"host\", \"\", \"\")\n\tuserAgent   = flag.String(\"U\", \"\", \"\")\n\n\toutput = flag.String(\"o\", \"\", \"\")\n\n\tc = flag.Int(\"c\", 50, \"\")\n\tn = flag.Int(\"n\", 200, \"\")\n\tq = flag.Float64(\"q\", 0, \"\")\n\tt = flag.Int(\"t\", 20, \"\")\n\tz = flag.Duration(\"z\", 0, \"\")\n\n\th2   = flag.Bool(\"h2\", false, \"\")\n\tcpus = flag.Int(\"cpus\", runtime.GOMAXPROCS(-1), \"\")\n\n\tdisableCompression = flag.Bool(\"disable-compression\", false, \"\")\n\tdisableKeepAlives  = flag.Bool(\"disable-keepalive\", false, \"\")\n\tdisableRedirects   = flag.Bool(\"disable-redirects\", false, \"\")\n\tproxyAddr          = flag.String(\"x\", \"\", \"\")\n)\n\nvar usage = `Usage: hey [options...] <url>\n\nOptions:\n  -n  Number of requests to run. Default is 200.\n  -c  Number of workers to run concurrently. Total number of requests cannot\n      be smaller than the concurrency level. Default is 50.\n  -q  Rate limit, in queries per second (QPS) per worker. Default is no rate limit.\n  -z  Duration of application to send requests. When duration is reached,\n      application stops and exits. If duration is specified, n is ignored.\n      Examples: -z 10s -z 3m.\n  -o  Output type. If none provided, a summary is printed.\n      \"csv\" is the only supported alternative. Dumps the response\n      metrics in comma-separated values format.\n\n  -m  HTTP method, one of GET, POST, PUT, DELETE, HEAD, OPTIONS.\n  -H  Custom HTTP header. You can specify as many as needed by repeating the flag.\n      For example, -H \"Accept: text/html\" -H \"Content-Type: application/xml\" .\n  -t  Timeout for each request in seconds. Default is 20, use 0 for infinite.\n  -A  HTTP Accept header.\n  -d  HTTP request body.\n  -D  HTTP request body from file. For example, /home/user/file.txt or ./file.txt.\n  -T  Content-type, defaults to \"text/html\".\n  -U  User-Agent, defaults to version \"hey/0.0.1\".\n  -a  Basic authentication, username:password.\n  -x  HTTP Proxy address as host:port.\n  -h2 Enable HTTP/2.\n\n  -host\tHTTP Host header.\n\n  -disable-compression  Disable compression.\n  -disable-keepalive    Disable keep-alive, prevents re-use of TCP\n                        connections between different HTTP requests.\n  -disable-redirects    Disable following of HTTP redirects\n  -cpus                 Number of used cpu cores.\n                        (default for current machine is %d cores)\n`\n\nfunc main() {\n\tflag.Usage = func() {\n\t\tfmt.Fprint(os.Stderr, fmt.Sprintf(usage, runtime.NumCPU()))\n\t}\n\n\tvar hs headerSlice\n\tflag.Var(&hs, \"H\", \"\")\n\n\tflag.Parse()\n\tif flag.NArg() < 1 {\n\t\tusageAndExit(\"\")\n\t}\n\n\truntime.GOMAXPROCS(*cpus)\n\tnum := *n\n\tconc := *c\n\tq := *q\n\tdur := *z\n\n\tif dur > 0 {\n\t\tnum = math.MaxInt32\n\t\tif conc <= 0 {\n\t\t\tusageAndExit(\"-c cannot be smaller than 1.\")\n\t\t}\n\t} else {\n\t\tif num <= 0 || conc <= 0 {\n\t\t\tusageAndExit(\"-n and -c cannot be smaller than 1.\")\n\t\t}\n\n\t\tif num < conc {\n\t\t\tusageAndExit(\"-n cannot be less than -c.\")\n\t\t}\n\t}\n\n\turl := flag.Args()[0]\n\tmethod := strings.ToUpper(*m)\n\n\t// set content-type\n\theader := make(http.Header)\n\theader.Set(\"Content-Type\", *contentType)\n\t// set any other additional headers\n\tif *headers != \"\" {\n\t\tusageAndExit(\"Flag '-h' is deprecated, please use '-H' instead.\")\n\t}\n\t// set any other additional repeatable headers\n\tfor _, h := range hs {\n\t\tmatch, err := parseInputWithRegexp(h, headerRegexp)\n\t\tif err != nil {\n\t\t\tusageAndExit(err.Error())\n\t\t}\n\t\theader.Set(match[1], match[2])\n\t}\n\n\tif *accept != \"\" {\n\t\theader.Set(\"Accept\", *accept)\n\t}\n\n\t// set basic auth if set\n\tvar username, password string\n\tif *authHeader != \"\" {\n\t\tmatch, err := parseInputWithRegexp(*authHeader, authRegexp)\n\t\tif err != nil {\n\t\t\tusageAndExit(err.Error())\n\t\t}\n\t\tusername, password = match[1], match[2]\n\t}\n\n\tvar bodyAll []byte\n\tif *body != \"\" {\n\t\tbodyAll = []byte(*body)\n\t}\n\tif *bodyFile != \"\" {\n\t\tslurp, err := ioutil.ReadFile(*bodyFile)\n\t\tif err != nil {\n\t\t\terrAndExit(err.Error())\n\t\t}\n\t\tbodyAll = slurp\n\t}\n\n\tvar proxyURL *gourl.URL\n\tif *proxyAddr != \"\" {\n\t\tvar err error\n\t\tproxyURL, err = gourl.Parse(*proxyAddr)\n\t\tif err != nil {\n\t\t\tusageAndExit(err.Error())\n\t\t}\n\t}\n\n\treq, err := http.NewRequest(method, url, nil)\n\tif err != nil {\n\t\tusageAndExit(err.Error())\n\t}\n\treq.ContentLength = int64(len(bodyAll))\n\tif username != \"\" || password != \"\" {\n\t\treq.SetBasicAuth(username, password)\n\t}\n\n\t// set host header if set\n\tif *hostHeader != \"\" {\n\t\treq.Host = *hostHeader\n\t}\n\n\tua := header.Get(\"User-Agent\")\n\tif ua == \"\" {\n\t\tua = heyUA\n\t} else {\n\t\tua += \" \" + heyUA\n\t}\n\theader.Set(\"User-Agent\", ua)\n\n\t// set userAgent header if set\n\tif *userAgent != \"\" {\n\t\tua = *userAgent + \" \" + heyUA\n\t\theader.Set(\"User-Agent\", ua)\n\t}\n\n\treq.Header = header\n\n\tw := &requester.Work{\n\t\tRequest:            req,\n\t\tRequestBody:        bodyAll,\n\t\tN:                  num,\n\t\tC:                  conc,\n\t\tQPS:                q,\n\t\tTimeout:            *t,\n\t\tDisableCompression: *disableCompression,\n\t\tDisableKeepAlives:  *disableKeepAlives,\n\t\tDisableRedirects:   *disableRedirects,\n\t\tH2:                 *h2,\n\t\tProxyAddr:          proxyURL,\n\t\tOutput:             *output,\n\t}\n\tw.Init()\n\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, os.Interrupt)\n\tgo func() {\n\t\t<-c\n\t\tw.Stop()\n\t}()\n\tif dur > 0 {\n\t\tgo func() {\n\t\t\ttime.Sleep(dur)\n\t\t\tw.Stop()\n\t\t}()\n\t}\n\tw.Run()\n}\n\nfunc errAndExit(msg string) {\n\tfmt.Fprintf(os.Stderr, \"%s\", msg)\n\tfmt.Fprintf(os.Stderr, \"\\n\")\n\tos.Exit(1)\n}\n\nfunc usageAndExit(msg string) {\n\tif msg != \"\" {\n\t\tfmt.Fprintf(os.Stderr, \"%s\", msg)\n\t\tfmt.Fprintf(os.Stderr, \"\\n\\n\")\n\t}\n\tflag.Usage()\n\tfmt.Fprintf(os.Stderr, \"\\n\")\n\tos.Exit(1)\n}\n\nfunc parseInputWithRegexp(input, regx string) ([]string, error) {\n\tre := regexp.MustCompile(regx)\n\tmatches := re.FindStringSubmatch(input)\n\tif len(matches) < 1 {\n\t\treturn nil, fmt.Errorf(\"could not parse the provided input; input = %v\", input)\n\t}\n\treturn matches, nil\n}\n\ntype headerSlice []string\n\nfunc (h *headerSlice) String() string {\n\treturn fmt.Sprintf(\"%s\", *h)\n}\n\nfunc (h *headerSlice) Set(value string) error {\n\t*h = append(*h, value)\n\treturn nil\n}\n"
  },
  {
    "path": "hey_test.go",
    "content": "// Copyright 2014 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage main\n\nimport (\n\t\"testing\"\n)\n\nfunc TestParseValidHeaderFlag(t *testing.T) {\n\tmatch, err := parseInputWithRegexp(\"X-Something: !Y10K:;(He@poverflow?)\", headerRegexp)\n\tif err != nil {\n\t\tt.Errorf(\"parseInputWithRegexp errored: %v\", err)\n\t}\n\tif got, want := match[1], \"X-Something\"; got != want {\n\t\tt.Errorf(\"got %v; want %v\", got, want)\n\t}\n\tif got, want := match[2], \"!Y10K:;(He@poverflow?)\"; got != want {\n\t\tt.Errorf(\"got %v; want %v\", got, want)\n\t}\n}\n\nfunc TestParseInvalidHeaderFlag(t *testing.T) {\n\t_, err := parseInputWithRegexp(\"X|oh|bad-input: badbadbad\", headerRegexp)\n\tif err == nil {\n\t\tt.Errorf(\"Header parsing errored; want no errors\")\n\t}\n}\n\nfunc TestParseValidAuthFlag(t *testing.T) {\n\tmatch, err := parseInputWithRegexp(\"_coo-kie_:!!bigmonster@1969sid\", authRegexp)\n\tif err != nil {\n\t\tt.Errorf(\"A valid auth flag was not parsed correctly: %v\", err)\n\t}\n\tif got, want := match[1], \"_coo-kie_\"; got != want {\n\t\tt.Errorf(\"got %v; want %v\", got, want)\n\t}\n\tif got, want := match[2], \"!!bigmonster@1969sid\"; got != want {\n\t\tt.Errorf(\"got %v; want %v\", got, want)\n\t}\n}\n\nfunc TestParseInvalidAuthFlag(t *testing.T) {\n\t_, err := parseInputWithRegexp(\"X|oh|bad-input: badbadbad\", authRegexp)\n\tif err == nil {\n\t\tt.Errorf(\"Header parsing errored; want no errors\")\n\t}\n}\n\nfunc TestParseAuthMetaCharacters(t *testing.T) {\n\t_, err := parseInputWithRegexp(\"plus+$*{:boom\", authRegexp)\n\tif err != nil {\n\t\tt.Errorf(\"Auth header with a plus sign in the user name errored: %v\", err)\n\t}\n}\n"
  },
  {
    "path": "requester/now_other.go",
    "content": "// Copyright 2018 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n// +build !windows\n\npackage requester\n\nimport \"time\"\n\nvar startTime = time.Now()\n\n// now returns time.Duration using stdlib time\nfunc now() time.Duration { return time.Since(startTime) }\n"
  },
  {
    "path": "requester/now_windows.go",
    "content": "// Copyright 2018 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage requester\n\nimport (\n\t\"syscall\"\n\t\"time\"\n\t\"unsafe\"\n)\n\n// now returns time.Duration using queryPerformanceCounter\nfunc now() time.Duration {\n\tvar now int64\n\tsyscall.Syscall(queryPerformanceCounterProc.Addr(), 1, uintptr(unsafe.Pointer(&now)), 0, 0)\n\treturn time.Duration(now) * time.Second / (time.Duration(qpcFrequency) * time.Nanosecond)\n}\n\n// precision timing\nvar (\n\tmodkernel32                   = syscall.NewLazyDLL(\"kernel32.dll\")\n\tqueryPerformanceFrequencyProc = modkernel32.NewProc(\"QueryPerformanceFrequency\")\n\tqueryPerformanceCounterProc   = modkernel32.NewProc(\"QueryPerformanceCounter\")\n\n\tqpcFrequency = queryPerformanceFrequency()\n)\n\n// queryPerformanceFrequency returns frequency in ticks per second\nfunc queryPerformanceFrequency() int64 {\n\tvar freq int64\n\tr1, _, _ := syscall.Syscall(queryPerformanceFrequencyProc.Addr(), 1, uintptr(unsafe.Pointer(&freq)), 0, 0)\n\tif r1 == 0 {\n\t\tpanic(\"call failed\")\n\t}\n\treturn freq\n}\n"
  },
  {
    "path": "requester/print.go",
    "content": "// Copyright 2014 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n/*\nHey supports two output formats: summary and CSV\n\nThe summary output presents a number of statistics about the requests in a\nhuman-readable format, including:\n- general statistics: requests/second, total runtime, and average, fastest, and slowest requests.\n- a response time histogram.\n- a percentile latency distribution.\n- statistics (average, fastest, slowest) on the stages of the requests.\n\nThe comma-separated CSV format is proceeded by a header, and consists of the following columns:\n1. response-time:\tTotal time taken for request (in seconds)\n2. DNS+dialup:\t\tTime taken to establish the TCP connection (in seconds)\n3. DNS:\t\t\t\tTime taken to do the DNS lookup (in seconds)\n4. Request-write:\tTime taken to write full request (in seconds)\n5. Response-delay: \tTime taken to first byte received (in seconds)\n6. Response-read:\tTime taken to read full response (in seconds)\n7. status-code:\t\tHTTP status code of the response (e.g. 200)\n8. offset:\t\t\tThe time since the start of the benchmark when the request was started. (in seconds)\n*/\npackage requester\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"strings\"\n\t\"text/template\"\n)\n\nfunc newTemplate(output string) *template.Template {\n\toutputTmpl := output\n\tswitch outputTmpl {\n\tcase \"\":\n\t\toutputTmpl = defaultTmpl\n\tcase \"csv\":\n\t\toutputTmpl = csvTmpl\n\t}\n\treturn template.Must(template.New(\"tmpl\").Funcs(tmplFuncMap).Parse(outputTmpl))\n}\n\nvar tmplFuncMap = template.FuncMap{\n\t\"formatNumber\":    formatNumber,\n\t\"formatNumberInt\": formatNumberInt,\n\t\"histogram\":       histogram,\n\t\"jsonify\":         jsonify,\n}\n\nfunc jsonify(v interface{}) string {\n\td, _ := json.Marshal(v)\n\treturn string(d)\n}\n\nfunc formatNumber(duration float64) string {\n\treturn fmt.Sprintf(\"%4.4f\", duration)\n}\n\nfunc formatNumberInt(duration int) string {\n\treturn fmt.Sprintf(\"%d\", duration)\n}\n\nfunc histogram(buckets []Bucket) string {\n\tmax := 0\n\tfor _, b := range buckets {\n\t\tif v := b.Count; v > max {\n\t\t\tmax = v\n\t\t}\n\t}\n\tres := new(bytes.Buffer)\n\tfor i := 0; i < len(buckets); i++ {\n\t\t// Normalize bar lengths.\n\t\tvar barLen int\n\t\tif max > 0 {\n\t\t\tbarLen = (buckets[i].Count*40 + max/2) / max\n\t\t}\n\t\tres.WriteString(fmt.Sprintf(\"  %4.3f [%v]\\t|%v\\n\", buckets[i].Mark, buckets[i].Count, strings.Repeat(barChar, barLen)))\n\t}\n\treturn res.String()\n}\n\nvar (\n\tdefaultTmpl = `\nSummary:\n  Total:\t{{ formatNumber .Total.Seconds }} secs\n  Slowest:\t{{ formatNumber .Slowest }} secs\n  Fastest:\t{{ formatNumber .Fastest }} secs\n  Average:\t{{ formatNumber .Average }} secs\n  Requests/sec:\t{{ formatNumber .Rps }}\n  {{ if gt .SizeTotal 0 }}\n  Total data:\t{{ .SizeTotal }} bytes\n  Size/request:\t{{ .SizeReq }} bytes{{ end }}\n\nResponse time histogram:\n{{ histogram .Histogram }}\n\nLatency distribution:{{ range .LatencyDistribution }}\n  {{ .Percentage }}%% in {{ formatNumber .Latency }} secs{{ end }}\n\nDetails (average, fastest, slowest):\n  DNS+dialup:\t{{ formatNumber .AvgConn }} secs, {{ formatNumber .ConnMax }} secs, {{ formatNumber .ConnMin }} secs\n  DNS-lookup:\t{{ formatNumber .AvgDNS }} secs, {{ formatNumber .DnsMax }} secs, {{ formatNumber .DnsMin }} secs\n  req write:\t{{ formatNumber .AvgReq }} secs, {{ formatNumber .ReqMax }} secs, {{ formatNumber .ReqMin }} secs\n  resp wait:\t{{ formatNumber .AvgDelay }} secs, {{ formatNumber .DelayMax }} secs, {{ formatNumber .DelayMin }} secs\n  resp read:\t{{ formatNumber .AvgRes }} secs, {{ formatNumber .ResMax }} secs, {{ formatNumber .ResMin }} secs\n\nStatus code distribution:{{ range $code, $num := .StatusCodeDist }}\n  [{{ $code }}]\t{{ $num }} responses{{ end }}\n\n{{ if gt (len .ErrorDist) 0 }}Error distribution:{{ range $err, $num := .ErrorDist }}\n  [{{ $num }}]\t{{ $err }}{{ end }}{{ end }}\n`\n\tcsvTmpl = `{{ $connLats := .ConnLats }}{{ $dnsLats := .DnsLats }}{{ $dnsLats := .DnsLats }}{{ $reqLats := .ReqLats }}{{ $delayLats := .DelayLats }}{{ $resLats := .ResLats }}{{ $statusCodeLats := .StatusCodes }}{{ $offsets := .Offsets}}response-time,DNS+dialup,DNS,Request-write,Response-delay,Response-read,status-code,offset{{ range $i, $v := .Lats }}\n{{ formatNumber $v }},{{ formatNumber (index $connLats $i) }},{{ formatNumber (index $dnsLats $i) }},{{ formatNumber (index $reqLats $i) }},{{ formatNumber (index $delayLats $i) }},{{ formatNumber (index $resLats $i) }},{{ formatNumberInt (index $statusCodeLats $i) }},{{ formatNumber (index $offsets $i) }}{{ end }}`\n)\n"
  },
  {
    "path": "requester/report.go",
    "content": "// Copyright 2014 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage requester\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"sort\"\n\t\"time\"\n)\n\nconst (\n\tbarChar = \"■\"\n)\n\n// We report for max 1M results.\nconst maxRes = 1000000\n\ntype report struct {\n\tavgTotal float64\n\tfastest  float64\n\tslowest  float64\n\taverage  float64\n\trps      float64\n\n\tavgConn     float64\n\tavgDNS      float64\n\tavgReq      float64\n\tavgRes      float64\n\tavgDelay    float64\n\tconnLats    []float64\n\tdnsLats     []float64\n\treqLats     []float64\n\tresLats     []float64\n\tdelayLats   []float64\n\toffsets     []float64\n\tstatusCodes []int\n\n\tresults chan *result\n\tdone    chan bool\n\ttotal   time.Duration\n\n\terrorDist map[string]int\n\tlats      []float64\n\tsizeTotal int64\n\tnumRes    int64\n\toutput    string\n\n\tw io.Writer\n}\n\nfunc newReport(w io.Writer, results chan *result, output string, n int) *report {\n\tcap := min(n, maxRes)\n\treturn &report{\n\t\toutput:      output,\n\t\tresults:     results,\n\t\tdone:        make(chan bool, 1),\n\t\terrorDist:   make(map[string]int),\n\t\tw:           w,\n\t\tconnLats:    make([]float64, 0, cap),\n\t\tdnsLats:     make([]float64, 0, cap),\n\t\treqLats:     make([]float64, 0, cap),\n\t\tresLats:     make([]float64, 0, cap),\n\t\tdelayLats:   make([]float64, 0, cap),\n\t\tlats:        make([]float64, 0, cap),\n\t\tstatusCodes: make([]int, 0, cap),\n\t}\n}\n\nfunc runReporter(r *report) {\n\t// Loop will continue until channel is closed\n\tfor res := range r.results {\n\t\tr.numRes++\n\t\tif res.err != nil {\n\t\t\tr.errorDist[res.err.Error()]++\n\t\t} else {\n\t\t\tr.avgTotal += res.duration.Seconds()\n\t\t\tr.avgConn += res.connDuration.Seconds()\n\t\t\tr.avgDelay += res.delayDuration.Seconds()\n\t\t\tr.avgDNS += res.dnsDuration.Seconds()\n\t\t\tr.avgReq += res.reqDuration.Seconds()\n\t\t\tr.avgRes += res.resDuration.Seconds()\n\t\t\tif len(r.resLats) < maxRes {\n\t\t\t\tr.lats = append(r.lats, res.duration.Seconds())\n\t\t\t\tr.connLats = append(r.connLats, res.connDuration.Seconds())\n\t\t\t\tr.dnsLats = append(r.dnsLats, res.dnsDuration.Seconds())\n\t\t\t\tr.reqLats = append(r.reqLats, res.reqDuration.Seconds())\n\t\t\t\tr.delayLats = append(r.delayLats, res.delayDuration.Seconds())\n\t\t\t\tr.resLats = append(r.resLats, res.resDuration.Seconds())\n\t\t\t\tr.statusCodes = append(r.statusCodes, res.statusCode)\n\t\t\t\tr.offsets = append(r.offsets, res.offset.Seconds())\n\t\t\t}\n\t\t\tif res.contentLength > 0 {\n\t\t\t\tr.sizeTotal += res.contentLength\n\t\t\t}\n\t\t}\n\t}\n\t// Signal reporter is done.\n\tr.done <- true\n}\n\nfunc (r *report) finalize(total time.Duration) {\n\tr.total = total\n\tr.rps = float64(r.numRes) / r.total.Seconds()\n\tr.average = r.avgTotal / float64(len(r.lats))\n\tr.avgConn = r.avgConn / float64(len(r.lats))\n\tr.avgDelay = r.avgDelay / float64(len(r.lats))\n\tr.avgDNS = r.avgDNS / float64(len(r.lats))\n\tr.avgReq = r.avgReq / float64(len(r.lats))\n\tr.avgRes = r.avgRes / float64(len(r.lats))\n\tr.print()\n}\n\nfunc (r *report) print() {\n\tbuf := &bytes.Buffer{}\n\tif err := newTemplate(r.output).Execute(buf, r.snapshot()); err != nil {\n\t\tlog.Println(\"error:\", err.Error())\n\t\treturn\n\t}\n\tr.printf(\"%s\", buf.String())\n\n\tr.printf(\"\\n\")\n}\n\nfunc (r *report) printf(s string, v ...interface{}) {\n\tfmt.Fprintf(r.w, s, v...)\n}\n\nfunc (r *report) snapshot() Report {\n\tsnapshot := Report{\n\t\tAvgTotal:    r.avgTotal,\n\t\tAverage:     r.average,\n\t\tRps:         r.rps,\n\t\tSizeTotal:   r.sizeTotal,\n\t\tAvgConn:     r.avgConn,\n\t\tAvgDNS:      r.avgDNS,\n\t\tAvgReq:      r.avgReq,\n\t\tAvgRes:      r.avgRes,\n\t\tAvgDelay:    r.avgDelay,\n\t\tTotal:       r.total,\n\t\tErrorDist:   r.errorDist,\n\t\tNumRes:      r.numRes,\n\t\tLats:        make([]float64, len(r.lats)),\n\t\tConnLats:    make([]float64, len(r.lats)),\n\t\tDnsLats:     make([]float64, len(r.lats)),\n\t\tReqLats:     make([]float64, len(r.lats)),\n\t\tResLats:     make([]float64, len(r.lats)),\n\t\tDelayLats:   make([]float64, len(r.lats)),\n\t\tOffsets:     make([]float64, len(r.lats)),\n\t\tStatusCodes: make([]int, len(r.lats)),\n\t}\n\n\tif len(r.lats) == 0 {\n\t\treturn snapshot\n\t}\n\n\tsnapshot.SizeReq = r.sizeTotal / int64(len(r.lats))\n\n\tcopy(snapshot.Lats, r.lats)\n\tcopy(snapshot.ConnLats, r.connLats)\n\tcopy(snapshot.DnsLats, r.dnsLats)\n\tcopy(snapshot.ReqLats, r.reqLats)\n\tcopy(snapshot.ResLats, r.resLats)\n\tcopy(snapshot.DelayLats, r.delayLats)\n\tcopy(snapshot.StatusCodes, r.statusCodes)\n\tcopy(snapshot.Offsets, r.offsets)\n\n\tsort.Float64s(r.lats)\n\tr.fastest = r.lats[0]\n\tr.slowest = r.lats[len(r.lats)-1]\n\n\tsort.Float64s(r.connLats)\n\tsort.Float64s(r.dnsLats)\n\tsort.Float64s(r.reqLats)\n\tsort.Float64s(r.resLats)\n\tsort.Float64s(r.delayLats)\n\n\tsnapshot.Histogram = r.histogram()\n\tsnapshot.LatencyDistribution = r.latencies()\n\n\tsnapshot.Fastest = r.fastest\n\tsnapshot.Slowest = r.slowest\n\tsnapshot.ConnMax = r.connLats[0]\n\tsnapshot.ConnMin = r.connLats[len(r.connLats)-1]\n\tsnapshot.DnsMax = r.dnsLats[0]\n\tsnapshot.DnsMin = r.dnsLats[len(r.dnsLats)-1]\n\tsnapshot.ReqMax = r.reqLats[0]\n\tsnapshot.ReqMin = r.reqLats[len(r.reqLats)-1]\n\tsnapshot.DelayMax = r.delayLats[0]\n\tsnapshot.DelayMin = r.delayLats[len(r.delayLats)-1]\n\tsnapshot.ResMax = r.resLats[0]\n\tsnapshot.ResMin = r.resLats[len(r.resLats)-1]\n\n\tstatusCodeDist := make(map[int]int, len(snapshot.StatusCodes))\n\tfor _, statusCode := range snapshot.StatusCodes {\n\t\tstatusCodeDist[statusCode]++\n\t}\n\tsnapshot.StatusCodeDist = statusCodeDist\n\n\treturn snapshot\n}\n\nfunc (r *report) latencies() []LatencyDistribution {\n\tpctls := []int{10, 25, 50, 75, 90, 95, 99}\n\tdata := make([]float64, len(pctls))\n\tj := 0\n\tfor i := 0; i < len(r.lats) && j < len(pctls); i++ {\n\t\tcurrent := i * 100 / len(r.lats)\n\t\tif current >= pctls[j] {\n\t\t\tdata[j] = r.lats[i]\n\t\t\tj++\n\t\t}\n\t}\n\tres := make([]LatencyDistribution, len(pctls))\n\tfor i := 0; i < len(pctls); i++ {\n\t\tif data[i] > 0 {\n\t\t\tres[i] = LatencyDistribution{Percentage: pctls[i], Latency: data[i]}\n\t\t}\n\t}\n\treturn res\n}\n\nfunc (r *report) histogram() []Bucket {\n\tbc := 10\n\tbuckets := make([]float64, bc+1)\n\tcounts := make([]int, bc+1)\n\tbs := (r.slowest - r.fastest) / float64(bc)\n\tfor i := 0; i < bc; i++ {\n\t\tbuckets[i] = r.fastest + bs*float64(i)\n\t}\n\tbuckets[bc] = r.slowest\n\tvar bi int\n\tvar max int\n\tfor i := 0; i < len(r.lats); {\n\t\tif r.lats[i] <= buckets[bi] {\n\t\t\ti++\n\t\t\tcounts[bi]++\n\t\t\tif max < counts[bi] {\n\t\t\t\tmax = counts[bi]\n\t\t\t}\n\t\t} else if bi < len(buckets)-1 {\n\t\t\tbi++\n\t\t}\n\t}\n\tres := make([]Bucket, len(buckets))\n\tfor i := 0; i < len(buckets); i++ {\n\t\tres[i] = Bucket{\n\t\t\tMark:      buckets[i],\n\t\t\tCount:     counts[i],\n\t\t\tFrequency: float64(counts[i]) / float64(len(r.lats)),\n\t\t}\n\t}\n\treturn res\n}\n\ntype Report struct {\n\tAvgTotal float64\n\tFastest  float64\n\tSlowest  float64\n\tAverage  float64\n\tRps      float64\n\n\tAvgConn  float64\n\tAvgDNS   float64\n\tAvgReq   float64\n\tAvgRes   float64\n\tAvgDelay float64\n\tConnMax  float64\n\tConnMin  float64\n\tDnsMax   float64\n\tDnsMin   float64\n\tReqMax   float64\n\tReqMin   float64\n\tResMax   float64\n\tResMin   float64\n\tDelayMax float64\n\tDelayMin float64\n\n\tLats        []float64\n\tConnLats    []float64\n\tDnsLats     []float64\n\tReqLats     []float64\n\tResLats     []float64\n\tDelayLats   []float64\n\tOffsets     []float64\n\tStatusCodes []int\n\n\tTotal time.Duration\n\n\tErrorDist      map[string]int\n\tStatusCodeDist map[int]int\n\tSizeTotal      int64\n\tSizeReq        int64\n\tNumRes         int64\n\n\tLatencyDistribution []LatencyDistribution\n\tHistogram           []Bucket\n}\n\ntype LatencyDistribution struct {\n\tPercentage int\n\tLatency    float64\n}\n\ntype Bucket struct {\n\tMark      float64\n\tCount     int\n\tFrequency float64\n}\n"
  },
  {
    "path": "requester/requester.go",
    "content": "// Copyright 2014 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n// Package requester provides commands to run load tests and display results.\npackage requester\n\nimport (\n\t\"bytes\"\n\t\"crypto/tls\"\n\t\"io\"\n\t\"net/http\"\n\t\"net/http/httptrace\"\n\t\"net/url\"\n\t\"os\"\n\t\"sync\"\n\t\"time\"\n\n\t\"golang.org/x/net/http2\"\n)\n\n// Max size of the buffer of result channel.\nconst maxResult = 1000000\nconst maxIdleConn = 500\n\ntype result struct {\n\terr           error\n\tstatusCode    int\n\toffset        time.Duration\n\tduration      time.Duration\n\tconnDuration  time.Duration // connection setup(DNS lookup + Dial up) duration\n\tdnsDuration   time.Duration // dns lookup duration\n\treqDuration   time.Duration // request \"write\" duration\n\tresDuration   time.Duration // response \"read\" duration\n\tdelayDuration time.Duration // delay between response and request\n\tcontentLength int64\n}\n\ntype Work struct {\n\t// Request is the request to be made.\n\tRequest *http.Request\n\n\tRequestBody []byte\n\n\t// RequestFunc is a function to generate requests. If it is nil, then\n\t// Request and RequestData are cloned for each request.\n\tRequestFunc func() *http.Request\n\n\t// N is the total number of requests to make.\n\tN int\n\n\t// C is the concurrency level, the number of concurrent workers to run.\n\tC int\n\n\t// H2 is an option to make HTTP/2 requests\n\tH2 bool\n\n\t// Timeout in seconds.\n\tTimeout int\n\n\t// Qps is the rate limit in queries per second.\n\tQPS float64\n\n\t// DisableCompression is an option to disable compression in response\n\tDisableCompression bool\n\n\t// DisableKeepAlives is an option to prevents re-use of TCP connections between different HTTP requests\n\tDisableKeepAlives bool\n\n\t// DisableRedirects is an option to prevent the following of HTTP redirects\n\tDisableRedirects bool\n\n\t// Output represents the output type. If \"csv\" is provided, the\n\t// output will be dumped as a csv stream.\n\tOutput string\n\n\t// ProxyAddr is the address of HTTP proxy server in the format on \"host:port\".\n\t// Optional.\n\tProxyAddr *url.URL\n\n\t// Writer is where results will be written. If nil, results are written to stdout.\n\tWriter io.Writer\n\n\tinitOnce sync.Once\n\tresults  chan *result\n\tstopCh   chan struct{}\n\tstart    time.Duration\n\n\treport *report\n}\n\nfunc (b *Work) writer() io.Writer {\n\tif b.Writer == nil {\n\t\treturn os.Stdout\n\t}\n\treturn b.Writer\n}\n\n// Init initializes internal data-structures\nfunc (b *Work) Init() {\n\tb.initOnce.Do(func() {\n\t\tb.results = make(chan *result, min(b.C*1000, maxResult))\n\t\tb.stopCh = make(chan struct{}, b.C)\n\t})\n}\n\n// Run makes all the requests, prints the summary. It blocks until\n// all work is done.\nfunc (b *Work) Run() {\n\tb.Init()\n\tb.start = now()\n\tb.report = newReport(b.writer(), b.results, b.Output, b.N)\n\t// Run the reporter first, it polls the result channel until it is closed.\n\tgo func() {\n\t\trunReporter(b.report)\n\t}()\n\tb.runWorkers()\n\tb.Finish()\n}\n\nfunc (b *Work) Stop() {\n\t// Send stop signal so that workers can stop gracefully.\n\tfor i := 0; i < b.C; i++ {\n\t\tb.stopCh <- struct{}{}\n\t}\n}\n\nfunc (b *Work) Finish() {\n\tclose(b.results)\n\ttotal := now() - b.start\n\t// Wait until the reporter is done.\n\t<-b.report.done\n\tb.report.finalize(total)\n}\n\nfunc (b *Work) makeRequest(c *http.Client) {\n\ts := now()\n\tvar size int64\n\tvar code int\n\tvar dnsStart, connStart, resStart, reqStart, delayStart time.Duration\n\tvar dnsDuration, connDuration, resDuration, reqDuration, delayDuration time.Duration\n\tvar req *http.Request\n\tif b.RequestFunc != nil {\n\t\treq = b.RequestFunc()\n\t} else {\n\t\treq = cloneRequest(b.Request, b.RequestBody)\n\t}\n\ttrace := &httptrace.ClientTrace{\n\t\tDNSStart: func(info httptrace.DNSStartInfo) {\n\t\t\tdnsStart = now()\n\t\t},\n\t\tDNSDone: func(dnsInfo httptrace.DNSDoneInfo) {\n\t\t\tdnsDuration = now() - dnsStart\n\t\t},\n\t\tGetConn: func(h string) {\n\t\t\tconnStart = now()\n\t\t},\n\t\tGotConn: func(connInfo httptrace.GotConnInfo) {\n\t\t\tif !connInfo.Reused {\n\t\t\t\tconnDuration = now() - connStart\n\t\t\t}\n\t\t\treqStart = now()\n\t\t},\n\t\tWroteRequest: func(w httptrace.WroteRequestInfo) {\n\t\t\treqDuration = now() - reqStart\n\t\t\tdelayStart = now()\n\t\t},\n\t\tGotFirstResponseByte: func() {\n\t\t\tdelayDuration = now() - delayStart\n\t\t\tresStart = now()\n\t\t},\n\t}\n\treq = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))\n\tresp, err := c.Do(req)\n\tif err == nil {\n\t\tsize = resp.ContentLength\n\t\tcode = resp.StatusCode\n\t\tio.Copy(io.Discard, resp.Body)\n\t\tresp.Body.Close()\n\t}\n\tt := now()\n\tresDuration = t - resStart\n\tfinish := t - s\n\tb.results <- &result{\n\t\toffset:        s,\n\t\tstatusCode:    code,\n\t\tduration:      finish,\n\t\terr:           err,\n\t\tcontentLength: size,\n\t\tconnDuration:  connDuration,\n\t\tdnsDuration:   dnsDuration,\n\t\treqDuration:   reqDuration,\n\t\tresDuration:   resDuration,\n\t\tdelayDuration: delayDuration,\n\t}\n}\n\nfunc (b *Work) runWorker(client *http.Client, n int) {\n\tvar throttle <-chan time.Time\n\tif b.QPS > 0 {\n\t\tticker := time.NewTicker(time.Duration(1e6/(b.QPS)) * time.Microsecond)\n\t\tdefer ticker.Stop()\n\t\tthrottle = ticker.C\n\t}\n\n\tif b.DisableRedirects {\n\t\tclient.CheckRedirect = func(req *http.Request, via []*http.Request) error {\n\t\t\treturn http.ErrUseLastResponse\n\t\t}\n\t}\n\tfor i := 0; i < n; i++ {\n\t\t// Check if application is stopped. Do not send into a closed channel.\n\t\tselect {\n\t\tcase <-b.stopCh:\n\t\t\treturn\n\t\tdefault:\n\t\t\tif b.QPS > 0 {\n\t\t\t\t<-throttle\n\t\t\t}\n\t\t\tb.makeRequest(client)\n\t\t}\n\t}\n}\n\nfunc (b *Work) runWorkers() {\n\tvar wg sync.WaitGroup\n\twg.Add(b.C)\n\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{\n\t\t\tInsecureSkipVerify: true,\n\t\t\tServerName:         b.Request.Host,\n\t\t},\n\t\tMaxIdleConnsPerHost: min(b.C, maxIdleConn),\n\t\tDisableCompression:  b.DisableCompression,\n\t\tDisableKeepAlives:   b.DisableKeepAlives,\n\t\tProxy:               http.ProxyURL(b.ProxyAddr),\n\t}\n\tif b.H2 {\n\t\thttp2.ConfigureTransport(tr)\n\t} else {\n\t\ttr.TLSNextProto = make(map[string]func(string, *tls.Conn) http.RoundTripper)\n\t}\n\tclient := &http.Client{Transport: tr, Timeout: time.Duration(b.Timeout) * time.Second}\n\n\t// Ignore the case where b.N % b.C != 0.\n\tfor i := 0; i < b.C; i++ {\n\t\tgo func() {\n\t\t\tb.runWorker(client, b.N/b.C)\n\t\t\twg.Done()\n\t\t}()\n\t}\n\twg.Wait()\n}\n\n// cloneRequest returns a clone of the provided *http.Request.\nfunc cloneRequest(r *http.Request, body []byte) *http.Request {\n\tr2 := r.Clone(r.Context())\n\tif len(body) > 0 {\n\t\tr2.Body = io.NopCloser(bytes.NewReader(body))\n\t}\n\treturn r2\n}\n\n"
  },
  {
    "path": "requester/requester_test.go",
    "content": "// Copyright 2014 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage requester\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestN(t *testing.T) {\n\tvar count int64\n\thandler := func(w http.ResponseWriter, r *http.Request) {\n\t\tatomic.AddInt64(&count, int64(1))\n\t}\n\tserver := httptest.NewServer(http.HandlerFunc(handler))\n\tdefer server.Close()\n\n\treq, _ := http.NewRequest(\"GET\", server.URL, nil)\n\tw := &Work{\n\t\tRequest: req,\n\t\tN:       20,\n\t\tC:       2,\n\t}\n\tw.Run()\n\tif count != 20 {\n\t\tt.Errorf(\"Expected to send 20 requests, found %v\", count)\n\t}\n}\n\nfunc TestQps(t *testing.T) {\n\tvar wg sync.WaitGroup\n\tvar count int64\n\thandler := func(w http.ResponseWriter, r *http.Request) {\n\t\tatomic.AddInt64(&count, int64(1))\n\t}\n\tserver := httptest.NewServer(http.HandlerFunc(handler))\n\tdefer server.Close()\n\n\treq, _ := http.NewRequest(\"GET\", server.URL, nil)\n\tw := &Work{\n\t\tRequest: req,\n\t\tN:       20,\n\t\tC:       2,\n\t\tQPS:     1,\n\t}\n\twg.Add(1)\n\ttime.AfterFunc(time.Second, func() {\n\t\tif count > 2 {\n\t\t\tt.Errorf(\"Expected to work at most 2 times, found %v\", count)\n\t\t}\n\t\twg.Done()\n\t})\n\tgo w.Run()\n\twg.Wait()\n}\n\nfunc TestRequest(t *testing.T) {\n\tvar uri, contentType, some, auth string\n\thandler := func(w http.ResponseWriter, r *http.Request) {\n\t\turi = r.RequestURI\n\t\tcontentType = r.Header.Get(\"Content-type\")\n\t\tsome = r.Header.Get(\"X-some\")\n\t\tauth = r.Header.Get(\"Authorization\")\n\t}\n\tserver := httptest.NewServer(http.HandlerFunc(handler))\n\tdefer server.Close()\n\n\theader := make(http.Header)\n\theader.Add(\"Content-type\", \"text/html\")\n\theader.Add(\"X-some\", \"value\")\n\treq, _ := http.NewRequest(\"GET\", server.URL, nil)\n\treq.Header = header\n\treq.SetBasicAuth(\"username\", \"password\")\n\tw := &Work{\n\t\tRequest: req,\n\t\tN:       1,\n\t\tC:       1,\n\t}\n\tw.Run()\n\tif uri != \"/\" {\n\t\tt.Errorf(\"Uri is expected to be /, %v is found\", uri)\n\t}\n\tif contentType != \"text/html\" {\n\t\tt.Errorf(\"Content type is expected to be text/html, %v is found\", contentType)\n\t}\n\tif some != \"value\" {\n\t\tt.Errorf(\"X-some header is expected to be value, %v is found\", some)\n\t}\n\tif auth != \"Basic dXNlcm5hbWU6cGFzc3dvcmQ=\" {\n\t\tt.Errorf(\"Basic authorization is not properly set\")\n\t}\n}\n\nfunc TestBody(t *testing.T) {\n\tvar count int64\n\thandler := func(w http.ResponseWriter, r *http.Request) {\n\t\tbody, _ := io.ReadAll(r.Body)\n\t\tif string(body) == \"Body\" {\n\t\t\tatomic.AddInt64(&count, 1)\n\t\t}\n\t}\n\tserver := httptest.NewServer(http.HandlerFunc(handler))\n\tdefer server.Close()\n\n\treq, _ := http.NewRequest(\"POST\", server.URL, bytes.NewBuffer([]byte(\"Body\")))\n\tw := &Work{\n\t\tRequest:     req,\n\t\tRequestBody: []byte(\"Body\"),\n\t\tN:           10,\n\t\tC:           1,\n\t}\n\tw.Run()\n\tif count != 10 {\n\t\tt.Errorf(\"Expected to work 10 times, found %v\", count)\n\t}\n}\n"
  }
]