From 4d7aa08b5e01ef1f509e3639df6be37fa29e2935 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 5 Sep 2023 07:47:23 +0000 Subject: [PATCH 01/41] build(deps): bump actions/checkout from 3 to 4 Bumps [actions/checkout](https://github.com/actions/checkout) from 3 to 4. - [Release notes](https://github.com/actions/checkout/releases) - [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md) - [Commits](https://github.com/actions/checkout/compare/v3...v4) --- updated-dependencies: - dependency-name: actions/checkout dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/coverage.yml | 2 +- .github/workflows/pull_request.yml | 2 +- .github/workflows/release.yml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index bd674cf2..b8772f65 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -26,7 +26,7 @@ jobs: uses: actions/setup-go@v4 with: go-version: "^1.18.0" - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Go Build Cache uses: actions/cache@v3 with: diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index cc78372f..001b9b96 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -16,7 +16,7 @@ jobs: run: | echo "::set-output name=go-build::$(go env GOCACHE)" echo "::set-output name=go-mod::$(go env GOMODCACHE)" - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Go Build Cache uses: actions/cache@v3 with: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ba276c48..cf7c90f8 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -23,7 +23,7 @@ jobs: build: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - uses: actions/cache@v3 env: cache-name: npm-cache From b844a53bed31444a3dd49724cc551538a5a6b4b4 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 13 Sep 2023 08:00:57 +0000 Subject: [PATCH 02/41] build(deps): bump docker/build-push-action from 4 to 5 Bumps [docker/build-push-action](https://github.com/docker/build-push-action) from 4 to 5. - [Release notes](https://github.com/docker/build-push-action/releases) - [Commits](https://github.com/docker/build-push-action/compare/v4...v5) --- updated-dependencies: - dependency-name: docker/build-push-action dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index cf7c90f8..db8d1104 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -84,7 +84,7 @@ jobs: REACT_APP_PREV_GO_VERSION: "${{ env.PREV_GO_VERSION }}" - name: Build and push image - uses: docker/build-push-action@v4 + uses: docker/build-push-action@v5 with: context: . file: ./build/release.dockerfile From 9dfca38fcdbf11cb37aa492a5fab3058d10afef6 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 13 Sep 2023 08:01:11 +0000 Subject: [PATCH 03/41] build(deps): bump docker/metadata-action from 4 to 5 Bumps [docker/metadata-action](https://github.com/docker/metadata-action) from 4 to 5. - [Release notes](https://github.com/docker/metadata-action/releases) - [Upgrade guide](https://github.com/docker/metadata-action/blob/master/UPGRADE.md) - [Commits](https://github.com/docker/metadata-action/compare/v4...v5) --- updated-dependencies: - dependency-name: docker/metadata-action dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index cf7c90f8..099e6c6b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -53,7 +53,7 @@ jobs: - name: Extract version metadata id: meta - uses: docker/metadata-action@v4 + uses: docker/metadata-action@v5 with: images: | x1unix/go-playground From fa906becae26c33b6d2d9cff72d4db4e5be46330 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 13 Sep 2023 08:01:15 +0000 Subject: [PATCH 04/41] build(deps): bump docker/setup-qemu-action from 2 to 3 Bumps [docker/setup-qemu-action](https://github.com/docker/setup-qemu-action) from 2 to 3. - [Release notes](https://github.com/docker/setup-qemu-action/releases) - [Commits](https://github.com/docker/setup-qemu-action/compare/v2...v3) --- updated-dependencies: - dependency-name: docker/setup-qemu-action dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index cf7c90f8..b858de2d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -63,7 +63,7 @@ jobs: type=semver,pattern={{major}}.{{minor}} - name: Set up QEMU - uses: docker/setup-qemu-action@v2 + uses: docker/setup-qemu-action@v3 - name: Set up Docker Buildx id: buildx From d1e2e717cf961d1d8b29d9cf6a89a7ae8595c7b9 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 14 Sep 2023 08:11:33 +0000 Subject: [PATCH 05/41] build(deps): bump docker/setup-buildx-action from 2 to 3 Bumps [docker/setup-buildx-action](https://github.com/docker/setup-buildx-action) from 2 to 3. - [Release notes](https://github.com/docker/setup-buildx-action/releases) - [Commits](https://github.com/docker/setup-buildx-action/compare/v2...v3) --- updated-dependencies: - dependency-name: docker/setup-buildx-action dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b858de2d..2d498c22 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -67,7 +67,7 @@ jobs: - name: Set up Docker Buildx id: buildx - uses: docker/setup-buildx-action@v2 + uses: docker/setup-buildx-action@v3 - uses: actions/setup-node@v3 with: From 8fa81c2f8d78a0dd91323630f1672666490bb531 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 14 Sep 2023 08:11:47 +0000 Subject: [PATCH 06/41] build(deps): bump docker/login-action from 2 to 3 Bumps [docker/login-action](https://github.com/docker/login-action) from 2 to 3. - [Release notes](https://github.com/docker/login-action/releases) - [Commits](https://github.com/docker/login-action/compare/v2...v3) --- updated-dependencies: - dependency-name: docker/login-action dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/release.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b858de2d..1b437026 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -39,13 +39,13 @@ jobs: echo "RELEASE_VERSION=${GITHUB_REF#refs/*/v}" >> $GITHUB_ENV - name: Login to Docker Hub - uses: docker/login-action@v2 + uses: docker/login-action@v3 with: username: ${{ secrets.DOCKERHUB_USERNAME }} password: ${{ secrets.DOCKERHUB_TOKEN }} - name: Login to GitHub Container Registry - uses: docker/login-action@v2 + uses: docker/login-action@v3 with: registry: ghcr.io username: ${{ github.actor }} From 91e126f1129f5b6cd490a94bd9593f60f06f2c38 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 17 Oct 2023 16:07:23 +0000 Subject: [PATCH 07/41] build(deps): bump @babel/traverse from 7.17.0 to 7.23.2 in /web Bumps [@babel/traverse](https://github.com/babel/babel/tree/HEAD/packages/babel-traverse) from 7.17.0 to 7.23.2. - [Release notes](https://github.com/babel/babel/releases) - [Changelog](https://github.com/babel/babel/blob/main/CHANGELOG.md) - [Commits](https://github.com/babel/babel/commits/v7.23.2/packages/babel-traverse) --- updated-dependencies: - dependency-name: "@babel/traverse" dependency-type: indirect ... Signed-off-by: dependabot[bot] --- web/yarn.lock | 140 +++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 127 insertions(+), 13 deletions(-) diff --git a/web/yarn.lock b/web/yarn.lock index 7a9b4fe3..fb13586a 100644 --- a/web/yarn.lock +++ b/web/yarn.lock @@ -25,6 +25,14 @@ dependencies: "@babel/highlight" "^7.16.7" +"@babel/code-frame@^7.22.13": + version "7.22.13" + resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.22.13.tgz#e3c1c099402598483b7a8c46a721d1038803755e" + integrity sha512-XktuhWlJ5g+3TJXc5upd9Ks1HutSArik6jf2eAjYFyIOf4ej3RN+184cZbzDvbPnuTJIUhPKKJE3cIsYTiAT3w== + dependencies: + "@babel/highlight" "^7.22.13" + chalk "^2.4.2" + "@babel/compat-data@^7.13.11", "@babel/compat-data@^7.16.4", "@babel/compat-data@^7.16.8": version "7.17.0" resolved "https://registry.yarnpkg.com/@babel/compat-data/-/compat-data-7.17.0.tgz#86850b8597ea6962089770952075dcaabb8dba34" @@ -69,6 +77,16 @@ jsesc "^2.5.1" source-map "^0.5.0" +"@babel/generator@^7.23.0": + version "7.23.0" + resolved "https://registry.yarnpkg.com/@babel/generator/-/generator-7.23.0.tgz#df5c386e2218be505b34837acbcb874d7a983420" + integrity sha512-lN85QRR+5IbYrMWM6Y4pE/noaQtg4pNiqeNGX60eqOfo6gtEj6uw/JagelB8vVztSd7R6M5n1+PQkDbHbBRU4g== + dependencies: + "@babel/types" "^7.23.0" + "@jridgewell/gen-mapping" "^0.3.2" + "@jridgewell/trace-mapping" "^0.3.17" + jsesc "^2.5.1" + "@babel/helper-annotate-as-pure@^7.16.7": version "7.16.7" resolved "https://registry.yarnpkg.com/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.16.7.tgz#bb2339a7534a9c128e3102024c60760a3a7f3862" @@ -136,6 +154,11 @@ dependencies: "@babel/types" "^7.16.7" +"@babel/helper-environment-visitor@^7.22.20": + version "7.22.20" + resolved "https://registry.yarnpkg.com/@babel/helper-environment-visitor/-/helper-environment-visitor-7.22.20.tgz#96159db61d34a29dba454c959f5ae4a649ba9167" + integrity sha512-zfedSIzFhat/gFhWfHtgWvlec0nqB9YEIVrpuwjruLlXfUSnA8cJB0miHKwqDnQ7d32aKo2xt88/xZptwxbfhA== + "@babel/helper-explode-assignable-expression@^7.16.7": version "7.16.7" resolved "https://registry.yarnpkg.com/@babel/helper-explode-assignable-expression/-/helper-explode-assignable-expression-7.16.7.tgz#12a6d8522fdd834f194e868af6354e8650242b7a" @@ -152,6 +175,14 @@ "@babel/template" "^7.16.7" "@babel/types" "^7.16.7" +"@babel/helper-function-name@^7.23.0": + version "7.23.0" + resolved "https://registry.yarnpkg.com/@babel/helper-function-name/-/helper-function-name-7.23.0.tgz#1f9a3cdbd5b2698a670c30d2735f9af95ed52759" + integrity sha512-OErEqsrxjZTJciZ4Oo+eoZqeW9UIiOcuYKRJA4ZAgV9myA+pOXhhmpfNCKjEH/auVfEYVFJ6y1Tc4r0eIApqiw== + dependencies: + "@babel/template" "^7.22.15" + "@babel/types" "^7.23.0" + "@babel/helper-get-function-arity@^7.16.7": version "7.16.7" resolved "https://registry.yarnpkg.com/@babel/helper-get-function-arity/-/helper-get-function-arity-7.16.7.tgz#ea08ac753117a669f1508ba06ebcc49156387419" @@ -166,6 +197,13 @@ dependencies: "@babel/types" "^7.16.7" +"@babel/helper-hoist-variables@^7.22.5": + version "7.22.5" + resolved "https://registry.yarnpkg.com/@babel/helper-hoist-variables/-/helper-hoist-variables-7.22.5.tgz#c01a007dac05c085914e8fb652b339db50d823bb" + integrity sha512-wGjk9QZVzvknA6yKIUURb8zY3grXCcOZt+/7Wcy8O2uctxhplmUPkOdlgoNhmdVee2c92JXbf1xpMtVNbfoxRw== + dependencies: + "@babel/types" "^7.22.5" + "@babel/helper-member-expression-to-functions@^7.16.7": version "7.16.7" resolved "https://registry.yarnpkg.com/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.16.7.tgz#42b9ca4b2b200123c3b7e726b0ae5153924905b0" @@ -247,11 +285,28 @@ dependencies: "@babel/types" "^7.16.7" +"@babel/helper-split-export-declaration@^7.22.6": + version "7.22.6" + resolved "https://registry.yarnpkg.com/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.22.6.tgz#322c61b7310c0997fe4c323955667f18fcefb91c" + integrity sha512-AsUnxuLhRYsisFiaJwvp1QF+I3KjD5FOxut14q/GzovUe6orHLesW2C7d754kRm53h5gqrz6sFl6sxc4BVtE/g== + dependencies: + "@babel/types" "^7.22.5" + +"@babel/helper-string-parser@^7.22.5": + version "7.22.5" + resolved "https://registry.yarnpkg.com/@babel/helper-string-parser/-/helper-string-parser-7.22.5.tgz#533f36457a25814cf1df6488523ad547d784a99f" + integrity sha512-mM4COjgZox8U+JcXQwPijIZLElkgEpO5rsERVDJTc2qfCDfERyob6k5WegS14SX18IIjv+XD+GrqNumY5JRCDw== + "@babel/helper-validator-identifier@^7.16.7": version "7.16.7" resolved "https://registry.yarnpkg.com/@babel/helper-validator-identifier/-/helper-validator-identifier-7.16.7.tgz#e8c602438c4a8195751243da9031d1607d247cad" integrity sha512-hsEnFemeiW4D08A5gUAZxLBTXpZ39P+a+DGDsHw1yxqyQ/jzFEnxf5uTEGp+3bzAbNOxU1paTgYS4ECU/IgfDw== +"@babel/helper-validator-identifier@^7.22.20": + version "7.22.20" + resolved "https://registry.yarnpkg.com/@babel/helper-validator-identifier/-/helper-validator-identifier-7.22.20.tgz#c4ae002c61d2879e724581d96665583dbc1dc0e0" + integrity sha512-Y4OZ+ytlatR8AI+8KZfKuL5urKp7qey08ha31L8b3BwewJAoJamTzyvxPR/5D+KkdJCGPq/+8TukHBlY10FX9A== + "@babel/helper-validator-option@^7.16.7": version "7.16.7" resolved "https://registry.yarnpkg.com/@babel/helper-validator-option/-/helper-validator-option-7.16.7.tgz#b203ce62ce5fe153899b617c08957de860de4d23" @@ -285,11 +340,25 @@ chalk "^2.0.0" js-tokens "^4.0.0" +"@babel/highlight@^7.22.13": + version "7.22.20" + resolved "https://registry.yarnpkg.com/@babel/highlight/-/highlight-7.22.20.tgz#4ca92b71d80554b01427815e06f2df965b9c1f54" + integrity sha512-dkdMCN3py0+ksCgYmGG8jKeGA/8Tk+gJwSYYlFGxG5lmhfKNoAy004YpLxpS1W2J8m/EK2Ew+yOs9pVRwO89mg== + dependencies: + "@babel/helper-validator-identifier" "^7.22.20" + chalk "^2.4.2" + js-tokens "^4.0.0" + "@babel/parser@^7.1.0", "@babel/parser@^7.14.7", "@babel/parser@^7.16.7", "@babel/parser@^7.17.0": version "7.17.0" resolved "https://registry.yarnpkg.com/@babel/parser/-/parser-7.17.0.tgz#f0ac33eddbe214e4105363bb17c3341c5ffcc43c" integrity sha512-VKXSCQx5D8S04ej+Dqsr1CzYvvWgf20jIw2D+YhQCrIlr2UZGaDds23Y0xg75/skOxpLCRpUZvk/1EAVkGoDOw== +"@babel/parser@^7.22.15", "@babel/parser@^7.23.0": + version "7.23.0" + resolved "https://registry.yarnpkg.com/@babel/parser/-/parser-7.23.0.tgz#da950e622420bf96ca0d0f2909cdddac3acd8719" + integrity sha512-vvPKKdMemU85V9WE/l5wZEmImpCtLqbnTvqDS2U1fJ96KrxoW7KrXhNsNCblQlg8Ck4b85yxdTyelsMUgFUXiw== + "@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression@^7.16.7": version "7.16.7" resolved "https://registry.yarnpkg.com/@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression/-/plugin-bugfix-safari-id-destructuring-collision-in-function-expression-7.16.7.tgz#4eda6d6c2a0aa79c70fa7b6da67763dfe2141050" @@ -1047,19 +1116,28 @@ "@babel/parser" "^7.16.7" "@babel/types" "^7.16.7" -"@babel/traverse@^7.13.0", "@babel/traverse@^7.16.7", "@babel/traverse@^7.16.8", "@babel/traverse@^7.17.0", "@babel/traverse@^7.7.2": - version "7.17.0" - resolved "https://registry.yarnpkg.com/@babel/traverse/-/traverse-7.17.0.tgz#3143e5066796408ccc880a33ecd3184f3e75cd30" - integrity sha512-fpFIXvqD6kC7c7PUNnZ0Z8cQXlarCLtCUpt2S1Dx7PjoRtCFffvOkHHSom+m5HIxMZn5bIBVb71lhabcmjEsqg== +"@babel/template@^7.22.15": + version "7.22.15" + resolved "https://registry.yarnpkg.com/@babel/template/-/template-7.22.15.tgz#09576efc3830f0430f4548ef971dde1350ef2f38" + integrity sha512-QPErUVm4uyJa60rkI73qneDacvdvzxshT3kksGqlGWYdOTIUOwJ7RDUL8sGqslY1uXWSL6xMFKEXDS3ox2uF0w== dependencies: - "@babel/code-frame" "^7.16.7" - "@babel/generator" "^7.17.0" - "@babel/helper-environment-visitor" "^7.16.7" - "@babel/helper-function-name" "^7.16.7" - "@babel/helper-hoist-variables" "^7.16.7" - "@babel/helper-split-export-declaration" "^7.16.7" - "@babel/parser" "^7.17.0" - "@babel/types" "^7.17.0" + "@babel/code-frame" "^7.22.13" + "@babel/parser" "^7.22.15" + "@babel/types" "^7.22.15" + +"@babel/traverse@^7.13.0", "@babel/traverse@^7.16.7", "@babel/traverse@^7.16.8", "@babel/traverse@^7.17.0", "@babel/traverse@^7.7.2": + version "7.23.2" + resolved "https://registry.yarnpkg.com/@babel/traverse/-/traverse-7.23.2.tgz#329c7a06735e144a506bdb2cad0268b7f46f4ad8" + integrity sha512-azpe59SQ48qG6nu2CzcMLbxUudtN+dOM9kDbUqGq3HXUJRlo7i8fvPoxQUzYgLZ4cMVmuZgm8vvBpNeRhd6XSw== + dependencies: + "@babel/code-frame" "^7.22.13" + "@babel/generator" "^7.23.0" + "@babel/helper-environment-visitor" "^7.22.20" + "@babel/helper-function-name" "^7.23.0" + "@babel/helper-hoist-variables" "^7.22.5" + "@babel/helper-split-export-declaration" "^7.22.6" + "@babel/parser" "^7.23.0" + "@babel/types" "^7.23.0" debug "^4.1.0" globals "^11.1.0" @@ -1071,6 +1149,15 @@ "@babel/helper-validator-identifier" "^7.16.7" to-fast-properties "^2.0.0" +"@babel/types@^7.22.15", "@babel/types@^7.22.5", "@babel/types@^7.23.0": + version "7.23.0" + resolved "https://registry.yarnpkg.com/@babel/types/-/types-7.23.0.tgz#8c1f020c9df0e737e4e247c0619f58c68458aaeb" + integrity sha512-0oIyUfKoI3mSqMvsxBdclDwxXKXAUA8v/apZbc+iSyARYou1o8ZGDxbUYyLFoW2arqS2jDGqJuZvv1d/io1axg== + dependencies: + "@babel/helper-string-parser" "^7.22.5" + "@babel/helper-validator-identifier" "^7.22.20" + to-fast-properties "^2.0.0" + "@bcoe/v8-coverage@^0.2.3": version "0.2.3" resolved "https://registry.yarnpkg.com/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz#75a2e8b51cb758a7553d6804a5932d7aace75c39" @@ -1541,11 +1628,25 @@ "@jridgewell/sourcemap-codec" "^1.4.10" "@jridgewell/trace-mapping" "^0.3.9" +"@jridgewell/gen-mapping@^0.3.2": + version "0.3.3" + resolved "https://registry.yarnpkg.com/@jridgewell/gen-mapping/-/gen-mapping-0.3.3.tgz#7e02e6eb5df901aaedb08514203b096614024098" + integrity sha512-HLhSWOLRi875zjjMG/r+Nv0oCW8umGb0BgEhyX3dDX3egwZtB8PqLnjz3yedt8R5StBrzcg4aBpnh8UA9D1BoQ== + dependencies: + "@jridgewell/set-array" "^1.0.1" + "@jridgewell/sourcemap-codec" "^1.4.10" + "@jridgewell/trace-mapping" "^0.3.9" + "@jridgewell/resolve-uri@^3.0.3": version "3.1.0" resolved "https://registry.yarnpkg.com/@jridgewell/resolve-uri/-/resolve-uri-3.1.0.tgz#2203b118c157721addfe69d47b70465463066d78" integrity sha512-F2msla3tad+Mfht5cJq7LSXcdudKTWCVYUgw6pLFOOHSTtZlj6SWNYAp+AhuqLmWdBO2X5hPrLcu8cVP8fy28w== +"@jridgewell/resolve-uri@^3.1.0": + version "3.1.1" + resolved "https://registry.yarnpkg.com/@jridgewell/resolve-uri/-/resolve-uri-3.1.1.tgz#c08679063f279615a3326583ba3a90d1d82cc721" + integrity sha512-dSYZh7HhCDtCKm4QakX0xFpsRDqjjtZf/kjI/v3T3Nwt5r8/qz/M19F9ySyOqU94SXBmeG9ttTul+YnR4LOxFA== + "@jridgewell/set-array@^1.0.1": version "1.1.2" resolved "https://registry.yarnpkg.com/@jridgewell/set-array/-/set-array-1.1.2.tgz#7c6cf998d6d20b914c0a55a91ae928ff25965e72" @@ -1564,6 +1665,11 @@ resolved "https://registry.yarnpkg.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.14.tgz#add4c98d341472a289190b424efbdb096991bb24" integrity sha512-XPSJHWmi394fuUuzDnGz1wiKqWfo1yXecHQMRf2l6hztTO+nPru658AyDngaBe7isIxEkRsPR3FZh+s7iVa4Uw== +"@jridgewell/sourcemap-codec@^1.4.14": + version "1.4.15" + resolved "https://registry.yarnpkg.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz#d7c6e6755c78567a951e04ab52ef0fd26de59f32" + integrity sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg== + "@jridgewell/trace-mapping@^0.3.0": version "0.3.2" resolved "https://registry.yarnpkg.com/@jridgewell/trace-mapping/-/trace-mapping-0.3.2.tgz#e051581782a770c30ba219634f2019241c5d3cde" @@ -1572,6 +1678,14 @@ "@jridgewell/resolve-uri" "^3.0.3" "@jridgewell/sourcemap-codec" "^1.4.10" +"@jridgewell/trace-mapping@^0.3.17": + version "0.3.19" + resolved "https://registry.yarnpkg.com/@jridgewell/trace-mapping/-/trace-mapping-0.3.19.tgz#f8a3249862f91be48d3127c3cfe992f79b4b8811" + integrity sha512-kf37QtfW+Hwx/buWGMPcR60iF9ziHa6r/CZJIHbmcm4+0qrXiVdxegAH0F6yddEVQ7zdkjcGCgCzUu+BcbhQxw== + dependencies: + "@jridgewell/resolve-uri" "^3.1.0" + "@jridgewell/sourcemap-codec" "^1.4.14" + "@jridgewell/trace-mapping@^0.3.9": version "0.3.14" resolved "https://registry.yarnpkg.com/@jridgewell/trace-mapping/-/trace-mapping-0.3.14.tgz#b231a081d8f66796e475ad588a1ef473112701ed" @@ -3091,7 +3205,7 @@ case-sensitive-paths-webpack-plugin@^2.4.0: resolved "https://registry.yarnpkg.com/case-sensitive-paths-webpack-plugin/-/case-sensitive-paths-webpack-plugin-2.4.0.tgz#db64066c6422eed2e08cc14b986ca43796dbc6d4" integrity sha512-roIFONhcxog0JSSWbvVAh3OocukmSgpqOH6YpMkCvav/ySIV3JKg4Dc8vYtQjYi/UxpNE36r/9v+VqTQqgkYmw== -chalk@^2.0.0, chalk@^2.4.1: +chalk@^2.0.0, chalk@^2.4.1, chalk@^2.4.2: version "2.4.2" resolved "https://registry.yarnpkg.com/chalk/-/chalk-2.4.2.tgz#cd42541677a54333cf541a49108c1432b44c9424" integrity sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ== From 95e3c7d0a2bbae205a3557733b3d364a3583d8bd Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 24 Oct 2023 07:37:05 +0000 Subject: [PATCH 08/41] build(deps): bump actions/setup-node from 3 to 4 Bumps [actions/setup-node](https://github.com/actions/setup-node) from 3 to 4. - [Release notes](https://github.com/actions/setup-node/releases) - [Commits](https://github.com/actions/setup-node/compare/v3...v4) --- updated-dependencies: - dependency-name: actions/setup-node dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ebcaa923..371edab9 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -69,7 +69,7 @@ jobs: id: buildx uses: docker/setup-buildx-action@v3 - - uses: actions/setup-node@v3 + - uses: actions/setup-node@v4 with: node-version: 'lts/gallium' From e6f1e852a372133860e602061824c11bb253dfd1 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 10 Nov 2023 23:37:40 +0000 Subject: [PATCH 09/41] build(deps): bump axios from 0.25.0 to 1.6.0 in /web Bumps [axios](https://github.com/axios/axios) from 0.25.0 to 1.6.0. - [Release notes](https://github.com/axios/axios/releases) - [Changelog](https://github.com/axios/axios/blob/v1.x/CHANGELOG.md) - [Commits](https://github.com/axios/axios/compare/v0.25.0...v1.6.0) --- updated-dependencies: - dependency-name: axios dependency-type: direct:production ... Signed-off-by: dependabot[bot] --- web/package.json | 2 +- web/yarn.lock | 34 +++++++++++++++++++++++++--------- 2 files changed, 26 insertions(+), 10 deletions(-) diff --git a/web/package.json b/web/package.json index df102c72..7ddd12ef 100644 --- a/web/package.json +++ b/web/package.json @@ -11,7 +11,7 @@ "@types/jest": "^27.4.0", "@types/react": "^17.0.39", "@types/react-dom": "^17.0.11", - "axios": "^0.25.0", + "axios": "^1.6.0", "circular-dependency-plugin": "^5.2.2", "clsx": "^1.1.1", "connected-react-router": "^6.9.2", diff --git a/web/yarn.lock b/web/yarn.lock index fb13586a..52e9691b 100644 --- a/web/yarn.lock +++ b/web/yarn.lock @@ -2854,12 +2854,14 @@ axe-core@^4.3.5: resolved "https://registry.yarnpkg.com/axe-core/-/axe-core-4.4.1.tgz#7dbdc25989298f9ad006645cd396782443757413" integrity sha512-gd1kmb21kwNuWr6BQz8fv6GNECPBnUasepcoLbekws23NVBLODdsClRZ+bQ8+9Uomf3Sm3+Vwn0oYG9NvwnJCw== -axios@^0.25.0: - version "0.25.0" - resolved "https://registry.yarnpkg.com/axios/-/axios-0.25.0.tgz#349cfbb31331a9b4453190791760a8d35b093e0a" - integrity sha512-cD8FOb0tRH3uuEe6+evtAbgJtfxr7ly3fQjYcMcuPlgkwVS9xboaVIpcDV+cYQe+yGykgwZCs1pzjntcGa6l5g== +axios@^1.6.0: + version "1.6.0" + resolved "https://registry.yarnpkg.com/axios/-/axios-1.6.0.tgz#f1e5292f26b2fd5c2e66876adc5b06cdbd7d2102" + integrity sha512-EZ1DYihju9pwVB+jg67ogm+Tmqc6JmhamRN6I4Zt8DfZu5lbcQGw3ozH9lFejSJgs/ibaef3A9PMXPLeefFGJg== dependencies: - follow-redirects "^1.14.7" + follow-redirects "^1.15.0" + form-data "^4.0.0" + proxy-from-env "^1.1.0" axobject-query@^2.2.0: version "2.2.0" @@ -4799,10 +4801,10 @@ flatted@^3.1.0: resolved "https://registry.yarnpkg.com/flatted/-/flatted-3.2.5.tgz#76c8584f4fc843db64702a6bd04ab7a8bd666da3" integrity sha512-WIWGi2L3DyTUvUrwRKgGi9TwxQMUEqPOPQBVi71R96jZXJdFskXEmf54BoZaS1kknGODoIGASGEzBUYdyMCBJg== -follow-redirects@^1.0.0, follow-redirects@^1.14.7: - version "1.14.8" - resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.14.8.tgz#016996fb9a11a100566398b1c6839337d7bfa8fc" - integrity sha512-1x0S9UVJHsQprFcEC/qnNzBLcIxsjAV905f/UkQxbclCsoTWlacCNOpQa/anodLl2uaEKFhfWOvM2Qg77+15zA== +follow-redirects@^1.0.0, follow-redirects@^1.15.0: + version "1.15.3" + resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.15.3.tgz#fe2f3ef2690afce7e82ed0b44db08165b207123a" + integrity sha512-1VzOtuEM8pC9SFU1E+8KfTjZyMztRsgEfwQl44z8A25uy13jSzTj6dyK2Df52iV0vgHCfBwLhDWevLn95w5v6Q== foreach@^2.0.5: version "2.0.5" @@ -4837,6 +4839,15 @@ form-data@^3.0.0: combined-stream "^1.0.8" mime-types "^2.1.12" +form-data@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/form-data/-/form-data-4.0.0.tgz#93919daeaf361ee529584b9b31664dc12c9fa452" + integrity sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww== + dependencies: + asynckit "^0.4.0" + combined-stream "^1.0.8" + mime-types "^2.1.12" + forwarded@0.2.0: version "0.2.0" resolved "https://registry.yarnpkg.com/forwarded/-/forwarded-0.2.0.tgz#2269936428aad4c15c7ebe9779a84bf0b2a81811" @@ -7663,6 +7674,11 @@ proxy-addr@~2.0.7: forwarded "0.2.0" ipaddr.js "1.9.1" +proxy-from-env@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/proxy-from-env/-/proxy-from-env-1.1.0.tgz#e102f16ca355424865755d2c9e8ea4f24d58c3e2" + integrity sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg== + psl@^1.1.33: version "1.8.0" resolved "https://registry.yarnpkg.com/psl/-/psl-1.8.0.tgz#9326f8bcfb013adcc005fdff056acce020e51c24" From 6c088eda9cb40b2bbfd06dd18c1c8daef14d1c34 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 7 Dec 2023 07:58:53 +0000 Subject: [PATCH 10/41] build(deps): bump actions/setup-go from 4 to 5 Bumps [actions/setup-go](https://github.com/actions/setup-go) from 4 to 5. - [Release notes](https://github.com/actions/setup-go/releases) - [Commits](https://github.com/actions/setup-go/compare/v4...v5) --- updated-dependencies: - dependency-name: actions/setup-go dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/coverage.yml | 2 +- .github/workflows/pull_request.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index b8772f65..ce6a8c87 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -23,7 +23,7 @@ jobs: echo "::set-output name=go-build::$(go env GOCACHE)" echo "::set-output name=go-mod::$(go env GOMODCACHE)" - name: Setup Go - uses: actions/setup-go@v4 + uses: actions/setup-go@v5 with: go-version: "^1.18.0" - uses: actions/checkout@v4 diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index 001b9b96..739841f3 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -42,7 +42,7 @@ jobs: run: yarn lint working-directory: ./web - name: Setup Go - uses: actions/setup-go@v4 + uses: actions/setup-go@v5 with: go-version: "^1.18.0" - name: golangci-lint From b3cde343d9582d4da29f470707ea0d0c328c7530 Mon Sep 17 00:00:00 2001 From: x1unix Date: Mon, 8 Jan 2024 14:23:22 -0500 Subject: [PATCH 11/41] chore: bump go and node versions --- build.mk | 2 +- build/Dockerfile | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/build.mk b/build.mk index 3376e415..f7953c89 100644 --- a/build.mk +++ b/build.mk @@ -1,6 +1,6 @@ GO ?= go YARN ?= yarn -GOROOT ?= $(shell go env GOROOT) +GOROOT ?= $(shell $(GO) env GOROOT) TOOLS ?= ./tools PUBLIC_DIR ?= $(UI)/public WEBWORKER_PKG ?= ./cmd/webworker diff --git a/build/Dockerfile b/build/Dockerfile index 66881ede..1ffd067f 100644 --- a/build/Dockerfile +++ b/build/Dockerfile @@ -1,4 +1,4 @@ -FROM node:17-alpine as ui-build +FROM node:20-alpine as ui-build COPY web /tmp/web WORKDIR /tmp/web ARG APP_VERSION=1.0.0 @@ -11,7 +11,7 @@ RUN yarn install --silent && \ REACT_APP_PREV_GO_VERSION=$PREV_GO_VERSION \ yarn build -FROM golang:1.19-alpine as build +FROM golang:1.21-alpine as build WORKDIR /tmp/playground COPY cmd ./cmd COPY pkg ./pkg @@ -25,7 +25,7 @@ RUN echo "Building server with version $APP_VERSION" && \ GOOS=js GOARCH=wasm go build -ldflags "-s -w" -trimpath -o ./worker.wasm ./cmd/webworker && \ cp $(go env GOROOT)/misc/wasm/wasm_exec.js . -FROM golang:1.19-alpine as production +FROM golang:1.21-alpine as production WORKDIR /opt/playground ENV GOROOT /usr/local/go ENV APP_CLEAN_INTERVAL=10m From b124c320ee5fb0a05a2ab8886598fcabceb7e222 Mon Sep 17 00:00:00 2001 From: x1unix Date: Mon, 8 Jan 2024 16:13:05 -0500 Subject: [PATCH 12/41] fix: replace CallImport with go:wasmimport --- internal/gorepl/uihost/downloads_js.go | 4 +- internal/gorepl/uihost/downloads_js.s | 11 -- internal/gorepl/uihost/runner_js.go | 4 +- internal/gorepl/uihost/runner_js.s | 11 -- internal/gowasm/browserfs/syscall_js.go | 14 +- internal/gowasm/browserfs/syscall_js.s | 36 ----- internal/gowasm/callback_js.go | 7 +- internal/gowasm/callback_js.s | 11 -- internal/gowasm/entrypoint_js.go | 4 +- internal/gowasm/entrypoint_js.s | 11 -- internal/gowasm/packagedb/syscall_js.go | 8 +- internal/gowasm/packagedb/syscall_js.s | 21 --- internal/gowasm/stdio_js.go | 4 +- internal/gowasm/stdio_js.s | 11 -- internal/gowasm/wlog/writer_js.go | 4 +- internal/gowasm/wlog/writer_js.s | 11 -- tools/gowasm-gen-import/main.go | 178 ---------------------- tools/gowasm-gen-import/template.gohtml | 13 -- web/src/lib/gowasm/syscall.ts | 8 +- web/src/services/gorepl/worker/binding.ts | 8 +- 20 files changed, 25 insertions(+), 354 deletions(-) delete mode 100644 internal/gorepl/uihost/downloads_js.s delete mode 100644 internal/gorepl/uihost/runner_js.s delete mode 100644 internal/gowasm/browserfs/syscall_js.s delete mode 100644 internal/gowasm/callback_js.s delete mode 100644 internal/gowasm/entrypoint_js.s delete mode 100644 internal/gowasm/packagedb/syscall_js.s delete mode 100644 internal/gowasm/stdio_js.s delete mode 100644 internal/gowasm/wlog/writer_js.s delete mode 100644 tools/gowasm-gen-import/main.go delete mode 100644 tools/gowasm-gen-import/template.gohtml diff --git a/internal/gorepl/uihost/downloads_js.go b/internal/gorepl/uihost/downloads_js.go index a5ed8e08..ffcd3608 100644 --- a/internal/gorepl/uihost/downloads_js.go +++ b/internal/gorepl/uihost/downloads_js.go @@ -1,6 +1,4 @@ package uihost -//go:generate go run ../../../tools/gowasm-gen-import $GOFILE - -//gowasm:import +//go:wasmimport gojs github.com/x1unix/go-playground/internal/gowasm/packagedb.onPackageManagerEvent func onPackageManagerEvent(e packageManagerEvent) diff --git a/internal/gorepl/uihost/downloads_js.s b/internal/gorepl/uihost/downloads_js.s deleted file mode 100644 index 6852f7f4..00000000 --- a/internal/gorepl/uihost/downloads_js.s +++ /dev/null @@ -1,11 +0,0 @@ -// FILE WAS GENERATED BY gowasm-gen-import, DO NOT EDIT! -// -// Source file: downloads_js.go - -#include "textflag.h" - -// func onPackageManagerEvent(e packageManagerEvent) -TEXT ·onPackageManagerEvent(SB), NOSPLIT, $0 - CallImport - RET - diff --git a/internal/gorepl/uihost/runner_js.go b/internal/gorepl/uihost/runner_js.go index 795935f0..6e6c0386 100644 --- a/internal/gorepl/uihost/runner_js.go +++ b/internal/gorepl/uihost/runner_js.go @@ -1,8 +1,6 @@ package uihost -//go:generate go run ../../../tools/gowasm-gen-import $GOFILE - // onProgramEvalStateChange reports program execution result to UI // -//gowasm:import +//go:wasmimport gojs github.com/x1unix/go-playground/internal/gorepl/uihost.onProgramEvalStateChange func onProgramEvalStateChange(state EvalState, msg string) diff --git a/internal/gorepl/uihost/runner_js.s b/internal/gorepl/uihost/runner_js.s deleted file mode 100644 index 44fc35b1..00000000 --- a/internal/gorepl/uihost/runner_js.s +++ /dev/null @@ -1,11 +0,0 @@ -// FILE WAS GENERATED BY gowasm-gen-import, DO NOT EDIT! -// -// Source file: runner_js.go - -#include "textflag.h" - -// func onProgramEvalStateChange(state EvalState, msg string) -TEXT ·onProgramEvalStateChange(SB), NOSPLIT, $0 - CallImport - RET - diff --git a/internal/gowasm/browserfs/syscall_js.go b/internal/gowasm/browserfs/syscall_js.go index 8a738e32..b97761f3 100644 --- a/internal/gowasm/browserfs/syscall_js.go +++ b/internal/gowasm/browserfs/syscall_js.go @@ -1,21 +1,19 @@ package browserfs -//go:generate go run ../../../tools/gowasm-gen-import $GOFILE - -//gowasm:import +//go:wasmimport gojs github.com/x1unix/go-playground/internal/gowasm/browserfs.stat func stat(name string, out *inode, cb int) -//gowasm:import +//go:wasmimport gojs github.com/x1unix/go-playground/internal/gowasm/browserfs.readDir func readDir(name string, out *[]inode, cb int) -//gowasm:import +//go:wasmimport gojs github.com/x1unix/go-playground/internal/gowasm/browserfs.readFile func readFile(fid uint64, out *[]byte, cb int) -//gowasm:import +//go:wasmimport gojs github.com/x1unix/go-playground/internal/gowasm/browserfs.writeFile func writeFile(name string, data []byte, cb int) -//gowasm:import +//go:wasmimport gojs github.com/x1unix/go-playground/internal/gowasm/browserfs.makeDir func makeDir(name string, cb int) -//gowasm:import +//go:wasmimport gojs github.com/x1unix/go-playground/internal/gowasm/browserfs.unlink func unlink(name string, cb int) diff --git a/internal/gowasm/browserfs/syscall_js.s b/internal/gowasm/browserfs/syscall_js.s deleted file mode 100644 index f9091e6e..00000000 --- a/internal/gowasm/browserfs/syscall_js.s +++ /dev/null @@ -1,36 +0,0 @@ -// FILE WAS GENERATED BY gowasm-gen-import, DO NOT EDIT! -// -// Source file: syscall_js.go - -#include "textflag.h" - -// func stat(name string, out *inode, cb int) -TEXT ·stat(SB), NOSPLIT, $0 - CallImport - RET - -// func readDir(name string, out *[]inode, cb int) -TEXT ·readDir(SB), NOSPLIT, $0 - CallImport - RET - -// func readFile(fid uint64, out *[]byte, cb int) -TEXT ·readFile(SB), NOSPLIT, $0 - CallImport - RET - -// func writeFile(name string, data []byte, cb int) -TEXT ·writeFile(SB), NOSPLIT, $0 - CallImport - RET - -// func makeDir(name string, cb int) -TEXT ·makeDir(SB), NOSPLIT, $0 - CallImport - RET - -// func unlink(name string, cb int) -TEXT ·unlink(SB), NOSPLIT, $0 - CallImport - RET - diff --git a/internal/gowasm/callback_js.go b/internal/gowasm/callback_js.go index d0314189..380b2ccf 100644 --- a/internal/gowasm/callback_js.go +++ b/internal/gowasm/callback_js.go @@ -1,16 +1,15 @@ package gowasm import ( - "github.com/x1unix/go-playground/internal/gowasm/wlog" "syscall/js" -) -//go:generate go run ../../tools/gowasm-gen-import $GOFILE + "github.com/x1unix/go-playground/internal/gowasm/wlog" +) // registerCallbackHandler registers a global callback // to receive capture async operations from JavaScript side. // -//gowasm:import +//go:wasmimport gojs github.com/x1unix/go-playground/internal/gowasm.registerCallbackHandler func registerCallbackHandler(fn js.Func) var callbackHandler = js.FuncOf(func(_ js.Value, args []js.Value) any { diff --git a/internal/gowasm/callback_js.s b/internal/gowasm/callback_js.s deleted file mode 100644 index a4f0a11f..00000000 --- a/internal/gowasm/callback_js.s +++ /dev/null @@ -1,11 +0,0 @@ -// FILE WAS GENERATED BY gowasm-gen-import, DO NOT EDIT! -// -// Source file: callback_js.go - -#include "textflag.h" - -// func registerCallbackHandler(fn js.Func) -TEXT ·registerCallbackHandler(SB), NOSPLIT, $0 - CallImport - RET - diff --git a/internal/gowasm/entrypoint_js.go b/internal/gowasm/entrypoint_js.go index b63548ee..3788b7f5 100644 --- a/internal/gowasm/entrypoint_js.go +++ b/internal/gowasm/entrypoint_js.go @@ -2,10 +2,8 @@ package gowasm import "syscall/js" -//go:generate go run ../../tools/gowasm-gen-import $GOFILE - // registerWorkerEntrypoint registers worker entrypoint in WASM host. // Entrypoint will be used by WASM host to call methods of a worker. // -//gowasm:import +//go:wasmimport gojs github.com/x1unix/go-playground/internal/gowasm.registerWorkerEntrypoint func registerWorkerEntrypoint(methods []string, handler js.Func) diff --git a/internal/gowasm/entrypoint_js.s b/internal/gowasm/entrypoint_js.s deleted file mode 100644 index 90ce0516..00000000 --- a/internal/gowasm/entrypoint_js.s +++ /dev/null @@ -1,11 +0,0 @@ -// FILE WAS GENERATED BY gowasm-gen-import, DO NOT EDIT! -// -// Source file: entrypoint_js.go - -#include "textflag.h" - -// func registerWorkerEntrypoint(methods []string, handler js.Func) -TEXT ·registerWorkerEntrypoint(SB), NOSPLIT, $0 - CallImport - RET - diff --git a/internal/gowasm/packagedb/syscall_js.go b/internal/gowasm/packagedb/syscall_js.go index af48d11d..bf02bca9 100644 --- a/internal/gowasm/packagedb/syscall_js.go +++ b/internal/gowasm/packagedb/syscall_js.go @@ -1,12 +1,10 @@ package packagedb -//go:generate go run ../../../tools/gowasm-gen-import $GOFILE - -//gowasm:import +//go:wasmimport gojs github.com/x1unix/go-playground/internal/gowasm/packagedb.registerPackage func lookupPackage(pkgName string, out *[]byte, cb int) -//gowasm:import +//go:wasmimport gojs github.com/x1unix/go-playground/internal/gowasm/packagedb.lookupPackage func registerPackage(pkgName, version string, cb int) -//gowasm:import +//go:wasmimport gojs github.com/x1unix/go-playground/internal/gowasm/packagedb.removePackage func removePackage(pkgName string, cb int) diff --git a/internal/gowasm/packagedb/syscall_js.s b/internal/gowasm/packagedb/syscall_js.s deleted file mode 100644 index 51529ab8..00000000 --- a/internal/gowasm/packagedb/syscall_js.s +++ /dev/null @@ -1,21 +0,0 @@ -// FILE WAS GENERATED BY gowasm-gen-import, DO NOT EDIT! -// -// Source file: syscall_js.go - -#include "textflag.h" - -// func lookupPackage(pkgName string, out *[]byte, cb int) -TEXT ·lookupPackage(SB), NOSPLIT, $0 - CallImport - RET - -// func registerPackage(pkgName, version string, cb int) -TEXT ·registerPackage(SB), NOSPLIT, $0 - CallImport - RET - -// func removePackage(pkgName string, cb int) -TEXT ·removePackage(SB), NOSPLIT, $0 - CallImport - RET - diff --git a/internal/gowasm/stdio_js.go b/internal/gowasm/stdio_js.go index 047f04ed..9833096f 100644 --- a/internal/gowasm/stdio_js.go +++ b/internal/gowasm/stdio_js.go @@ -1,6 +1,4 @@ package gowasm -//go:generate go run ../../tools/gowasm-gen-import $GOFILE - -//gowasm:import +//go:wasmimport gojs github.com/x1unix/go-playground/internal/gowasm.wasmConsoleWrite func wasmConsoleWrite(fd int, data []byte) diff --git a/internal/gowasm/stdio_js.s b/internal/gowasm/stdio_js.s deleted file mode 100644 index 7c4ccbc9..00000000 --- a/internal/gowasm/stdio_js.s +++ /dev/null @@ -1,11 +0,0 @@ -// FILE WAS GENERATED BY gowasm-gen-import, DO NOT EDIT! -// -// Source file: stdio_js.go - -#include "textflag.h" - -// func wasmConsoleWrite(fd int, data []byte) -TEXT ·wasmConsoleWrite(SB), NOSPLIT, $0 - CallImport - RET - diff --git a/internal/gowasm/wlog/writer_js.go b/internal/gowasm/wlog/writer_js.go index 01e0350f..871497be 100644 --- a/internal/gowasm/wlog/writer_js.go +++ b/internal/gowasm/wlog/writer_js.go @@ -13,9 +13,7 @@ var ( StdDebug io.Writer = newLogWriter(logLevelDebug) ) -//go:generate go run ../../../tools/gowasm-gen-import $GOFILE - -//gowasm:import +//go:wasmimport gojs github.com/x1unix/go-playground/internal/gowasm/wlog.logWrite func logWrite(level uint8, data []byte) const ( diff --git a/internal/gowasm/wlog/writer_js.s b/internal/gowasm/wlog/writer_js.s deleted file mode 100644 index f567e7b2..00000000 --- a/internal/gowasm/wlog/writer_js.s +++ /dev/null @@ -1,11 +0,0 @@ -// FILE WAS GENERATED BY gowasm-gen-import, DO NOT EDIT! -// -// Source file: writer_js.go - -#include "textflag.h" - -// func logWrite(level uint8, data []byte) -TEXT ·logWrite(SB), NOSPLIT, $0 - CallImport - RET - diff --git a/tools/gowasm-gen-import/main.go b/tools/gowasm-gen-import/main.go deleted file mode 100644 index bb438209..00000000 --- a/tools/gowasm-gen-import/main.go +++ /dev/null @@ -1,178 +0,0 @@ -package main - -import ( - "bytes" - _ "embed" - "fmt" - "github.com/spf13/cobra" - "go/ast" - "go/parser" - "go/token" - "io" - "os" - "path/filepath" - "strings" - "text/template" - "time" - - "github.com/samber/lo" -) - -const ( - importDirective = "gowasm:import" - programName = "gowasm-gen-import" -) - -//go:embed template.gohtml -var tplData []byte - -type exportFuncDecl struct { - Name string - Signature string -} - -type fileTemplateData struct { - SourceFile string - CreatedAt time.Time - ProgramName string - Declarations []exportFuncDecl -} - -func main() { - dryRun := false - cmd := cobra.Command{ - Use: programName + " [flags] filename", - Short: programName + " - Generate assembly file for external WASM functions.", - Example: programName + " internal/gowasm/syscall_js.go", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - return run(args[0], dryRun) - }, - SilenceErrors: true, - SilenceUsage: true, - } - cmd.Flags(). - BoolVarP(&dryRun, "dry-run", "d", false, "Output to stdout instead of file") - - if err := cmd.Execute(); err != nil { - _, _ = fmt.Fprintln(os.Stderr, "ERROR:", err) - os.Exit(1) - return - } -} - -func run(fileName string, dryRun bool) error { - tpl, err := template.New("gowasm-import-template.s").Parse(string(tplData)) - if err != nil { - return fmt.Errorf("failed to load assembly file template: %w", err) - } - - if filepath.Ext(fileName) != ".go" { - return fmt.Errorf("file %s is not a Go source file", fileName) - } - - data, err := os.ReadFile(fileName) - if err != nil { - return err - } - - fset := token.NewFileSet() - p, err := parser.ParseFile(fset, fileName, data, parser.ParseComments|parser.SkipObjectResolution) - if err != nil { - return err - } - - if len(p.Decls) == 0 { - return nil - } - - decls := traverseDecls(data, p.Decls) - if len(decls) == 0 { - return nil - } - - var writer io.WriteCloser = os.Stdout - destFileName := strings.TrimSuffix(fileName, filepath.Ext(fileName)) + ".s" - if !dryRun { - writer, err = os.OpenFile(destFileName, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644) - if err != nil { - return fmt.Errorf("failed to create output file: %w", err) - } - defer writer.Close() - } - - if err = writeAsmFile(tpl, writer, fileName, decls); err != nil { - return err - } - - if !dryRun { - absPath, err := filepath.Abs(destFileName) - if err != nil { - absPath = destFileName - } - - fmt.Println("Generated: ", absPath) - } - return nil -} - -func writeAsmFile(tpl *template.Template, dst io.Writer, srcFile string, decls []exportFuncDecl) error { - tplData := &fileTemplateData{ - SourceFile: filepath.Base(srcFile), - CreatedAt: time.Now(), - ProgramName: programName, - Declarations: decls, - } - - if err := tpl.Execute(dst, tplData); err != nil { - return fmt.Errorf("failed to generate file: %w", err) - } - - return nil -} - -func traverseDecls(src []byte, decls []ast.Decl) []exportFuncDecl { - if len(decls) == 0 { - return nil - } - - result := make([]exportFuncDecl, 0, len(decls)) - for _, decl := range decls { - funcDecl, ok := decl.(*ast.FuncDecl) - if !ok { - continue - } - - if !hasCallExportDirective(funcDecl.Doc) { - continue - } - - // parser skips first character - start := funcDecl.Pos() - 1 - end := funcDecl.End() - - result = append(result, exportFuncDecl{ - Name: funcDecl.Name.String(), - Signature: string(bytes.TrimSpace(src[start:end])), - }) - } - - return result -} - -func hasCallExportDirective(doc *ast.CommentGroup) bool { - if doc == nil { - return false - } - - directives := lo.Filter( - lo.Map(doc.List, func(comment *ast.Comment, _ int) string { - return strings.TrimSpace(strings.TrimPrefix(comment.Text, "//")) - }), - func(comment string, _ int) bool { - return comment == importDirective - }, - ) - - return len(directives) != 0 -} diff --git a/tools/gowasm-gen-import/template.gohtml b/tools/gowasm-gen-import/template.gohtml deleted file mode 100644 index 961d6d46..00000000 --- a/tools/gowasm-gen-import/template.gohtml +++ /dev/null @@ -1,13 +0,0 @@ -// FILE WAS GENERATED BY {{ .ProgramName }}, DO NOT EDIT! -// -// Source file: {{ .SourceFile }} - -#include "textflag.h" - -{{ range $i, $decl := .Declarations -}} -// {{ $decl.Signature }} -TEXT ·{{$decl.Name}}(SB), NOSPLIT, $0 - CallImport - RET - -{{end -}} diff --git a/web/src/lib/gowasm/syscall.ts b/web/src/lib/gowasm/syscall.ts index 21da738d..28f6ecfe 100644 --- a/web/src/lib/gowasm/syscall.ts +++ b/web/src/lib/gowasm/syscall.ts @@ -1,6 +1,6 @@ -import {WasmExport, Package, PackageBinding} from '~/lib/gowasm/binder'; -import {GoWrapper, js, StackReader} from '~/lib/go'; -import {Errno, SyscallError} from '~/lib/go/pkg/syscall'; +import { WasmExport, Package, PackageBinding } from '~/lib/gowasm/binder'; +import { GoWrapper, js, StackReader } from '~/lib/go'; +import { Errno, SyscallError } from '~/lib/go/pkg/syscall'; // list of syscall errors which should not be logged. const suppressedErrors = new Set([ @@ -39,7 +39,7 @@ export default class SyscallHelper extends PackageBinding { } if (this.debug) { - console.log('SyscallHelper: sendCallbackResult', { callbackId, result}); + console.log('SyscallHelper: sendCallbackResult', { callbackId, result }); } this.go.callFunc(this.callbackFunc, [callbackId, result]); diff --git a/web/src/services/gorepl/worker/binding.ts b/web/src/services/gorepl/worker/binding.ts index 59a71155..1987ce41 100644 --- a/web/src/services/gorepl/worker/binding.ts +++ b/web/src/services/gorepl/worker/binding.ts @@ -1,4 +1,4 @@ -import {Package, PackageBinding, WasmExport} from "~/lib/gowasm"; +import { Package, PackageBinding, WasmExport } from "~/lib/gowasm"; import { Bool, GoStringType, @@ -8,8 +8,8 @@ import { Struct, Uint8 } from "~/lib/go"; -import {newPackageSymbolFunc} from "~/lib/gowasm/utils"; -import {EvalEventHandler, EvalState, PackageManagerEvent} from "./types"; +import { newPackageSymbolFunc } from "~/lib/gowasm/utils"; +import { EvalEventHandler, EvalState, PackageManagerEvent } from "./types"; const pkgName = 'github.com/x1unix/go-playground/internal/gorepl/uihost'; const sym = newPackageSymbolFunc(pkgName); @@ -51,6 +51,6 @@ export class UIHostBinding extends PackageBinding { const state = stack.next(Uint8); const message = stack.next(GoStringType); - this.handler.onProgramEvalStateChange({state, message}); + this.handler.onProgramEvalStateChange({ state, message }); } } From 0e829ee228646e96493e3884d4126d01ef4bb0ac Mon Sep 17 00:00:00 2001 From: x1unix Date: Mon, 8 Jan 2024 16:15:12 -0500 Subject: [PATCH 13/41] fix: fix makefile rules --- build.mk | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/build.mk b/build.mk index f7953c89..20fe9dd6 100644 --- a/build.mk +++ b/build.mk @@ -59,11 +59,11 @@ copy-wasm-exec: .PHONY:build-webworker build-webworker: - $(call build_wasm_worker,$(WEBWORKER_PKG),'worker.wasm') + $(call build_wasm_worker,$(WEBWORKER_PKG),worker.wasm) .PHONY:go-repl go-repl: - $(call build_wasm_worker,$(INTERPRETER_PKG),'go-repl.wasm') + $(call build_wasm_worker,$(INTERPRETER_PKG),go-repl.wasm) .PHONY:build-wasm build-wasm: copy-wasm-exec build-webworker go-repl From c0adac4a2e925128c7bd7f8600c2b9ff2305834f Mon Sep 17 00:00:00 2001 From: x1unix Date: Mon, 8 Jan 2024 16:27:53 -0500 Subject: [PATCH 14/41] chore: require Go 1.21+ --- README.md | 2 +- build.mk | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 0702adbe..ce254d11 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,7 @@ See [wiki](https://github.com/x1unix/go-playground/wiki/Docker) for usage info. ### Building from source -Service can be built from source (**Go 1.17+** and **Node.js** required): +Service can be built from source (**Go 1.21+** and **Node.js** required): ```bash git clone https://github.com/x1unix/go-playground.git diff --git a/build.mk b/build.mk index 20fe9dd6..c56c02f7 100644 --- a/build.mk +++ b/build.mk @@ -6,6 +6,8 @@ PUBLIC_DIR ?= $(UI)/public WEBWORKER_PKG ?= ./cmd/webworker INTERPRETER_PKG ?= ./cmd/go-repl +MIN_GO_VERSION ?= 1.21 + define build_wasm_worker @echo ":: Building WebAssembly worker '$(1)' ..." GOOS=js GOARCH=wasm $(GO) build -ldflags "-s -w" -trimpath \ @@ -27,6 +29,10 @@ clean: .PHONY:check-go check-go: $(call check_tool,$(GO),'GO') + @if [ "$$(printf '%s\n' "$$($(GO) version)" $(MIN_GO_VERSION) | sort -V | head -n1)" != "1.21" ]; then \ + echo "Error: Go version should be $(MIN_GO_VERSION) or above"; \ + exit 1; \ + fi .PHONY:check-yarn check-yarn: From 3c9e793dc8a9b07e50e86bd936a8400667b27c04 Mon Sep 17 00:00:00 2001 From: x1unix Date: Mon, 8 Jan 2024 16:30:56 -0500 Subject: [PATCH 15/41] chore: update stdlib index --- data/packages.json | 213 +++++++++++++++++++++++++++++++++------------ 1 file changed, 157 insertions(+), 56 deletions(-) diff --git a/data/packages.json b/data/packages.json index 38c9243e..75a8aa70 100644 --- a/data/packages.json +++ b/data/packages.json @@ -14,13 +14,20 @@ }, { "name": "zip", - "synopsis": "Package zip provides support for reading and writing ZIP archives.\n\nSee: https://www.pkware.com/appnote\n\nThis package does not support disk spanning.\n\nA note about ZIP64:\n\nTo be backwards compatible the FileHeader has both 32 and 64 bit Size\nfields. The 64 bit fields will always contain the correct value and\nfor normal archives both fields will be the same. For files requiring\nthe ZIP64 format the 32 bit fields will be 0xffffffff and the 64 bit\nfields must be used instead.\n\n[\"archive/zip\" on pkg.go.dev](https://pkg.go.dev/archive/zip)", + "synopsis": "Package zip provides support for reading and writing ZIP archives.\n\nSee the [ZIP specification] for details.\n\nThis package does not support disk spanning.\n\nA note about ZIP64:\n\nTo be backwards compatible the FileHeader has both 32 and 64 bit Size\nfields. The 64 bit fields will always contain the correct value and\nfor normal archives both fields will be the same. For files requiring\nthe ZIP64 format the 32 bit fields will be 0xffffffff and the 64 bit\nfields must be used instead.\n\n[ZIP specification]: https://www.pkware.com/appnote\n\n[\"archive/zip\" on pkg.go.dev](https://pkg.go.dev/archive/zip)", "url": "https://pkg.go.dev/archive/zip", "path": "archive/zip", "children": [] } ] }, + { + "name": "arena", + "synopsis": "The arena package provides the ability to allocate memory for a collection\nof Go values and free that space manually all at once, safely. The purpose\nof this functionality is to improve efficiency: manually freeing memory\nbefore a garbage collection delays that cycle. Less frequent cycles means\nthe CPU cost of the garbage collector is incurred less frequently.\n\nThis functionality in this package is mostly captured in the Arena type.\nArenas allocate large chunks of memory for Go values, so they're likely to\nbe inefficient for allocating only small amounts of small Go values. They're\nbest used in bulk, on the order of MiB of memory allocated on each use.\n\nNote that by allowing for this limited form of manual memory allocation\nthat use-after-free bugs are possible with regular Go values. This package\nlimits the impact of these use-after-free bugs by preventing reuse of freed\nmemory regions until the garbage collector is able to determine that it is\nsafe. Typically, a use-after-free bug will result in a fault and a helpful\nerror message, but this package reserves the right to not force a fault on\nfreed memory. That means a valid implementation of this package is to just\nallocate all memory the way the runtime normally would, and in fact, it\nreserves the right to occasionally do so for some Go values.\n\n[\"arena\" on pkg.go.dev](https://pkg.go.dev/arena)", + "url": "https://pkg.go.dev/arena", + "path": "arena", + "children": [] + }, { "name": "bufio", "synopsis": "Package bufio implements buffered I/O. It wraps an io.Reader or io.Writer\nobject, creating another object (Reader or Writer) that also implements\nthe interface but provides buffering and some help for textual I/O.\n\n[\"bufio\" on pkg.go.dev](https://pkg.go.dev/bufio)", @@ -37,11 +44,40 @@ }, { "name": "bytes", - "synopsis": "Package bytes implements functions for the manipulation of byte slices.\nIt is analogous to the facilities of the strings package.\n\n[\"bytes\" on pkg.go.dev](https://pkg.go.dev/bytes)", + "synopsis": "Package bytes implements functions for the manipulation of byte slices.\nIt is analogous to the facilities of the [strings] package.\n\n[\"bytes\" on pkg.go.dev](https://pkg.go.dev/bytes)", "url": "https://pkg.go.dev/bytes", "path": "bytes", "children": [] }, + { + "name": "cmd", + "synopsis": "", + "url": "https://pkg.go.dev/cmd", + "path": "cmd", + "children": [ + { + "name": "building_Go_requires_Go_1_17_13_or_later", + "synopsis": "\n[\"cmd/dist\" on pkg.go.dev](https://pkg.go.dev/cmd/dist)", + "url": "https://pkg.go.dev/cmd/dist", + "path": "cmd/dist", + "children": [] + }, + { + "name": "tools", + "synopsis": "\n[\"cmd/tools\" on pkg.go.dev](https://pkg.go.dev/cmd/tools)", + "url": "https://pkg.go.dev/cmd/tools", + "path": "cmd/tools", + "children": [] + } + ] + }, + { + "name": "cmp", + "synopsis": "Package cmp provides types and functions related to comparing\nordered values.\n\n[\"cmp\" on pkg.go.dev](https://pkg.go.dev/cmp)", + "url": "https://pkg.go.dev/cmp", + "path": "cmp", + "children": [] + }, { "name": "compress", "synopsis": "", @@ -71,7 +107,7 @@ }, { "name": "lzw", - "synopsis": "Package lzw implements the Lempel-Ziv-Welch compressed data format,\ndescribed in T. A. Welch, ``A Technique for High-Performance Data\nCompression'', Computer, 17(6) (June 1984), pp 8-19.\n\nIn particular, it implements LZW as used by the GIF and PDF file\nformats, which means variable-width codes up to 12 bits and the first\ntwo non-literal codes are a clear code and an EOF code.\n\nThe TIFF file format uses a similar but incompatible version of the LZW\nalgorithm. See the golang.org/x/image/tiff/lzw package for an\nimplementation.\n\n[\"compress/lzw\" on pkg.go.dev](https://pkg.go.dev/compress/lzw)", + "synopsis": "Package lzw implements the Lempel-Ziv-Welch compressed data format,\ndescribed in T. A. Welch, “A Technique for High-Performance Data\nCompression”, Computer, 17(6) (June 1984), pp 8-19.\n\nIn particular, it implements LZW as used by the GIF and PDF file\nformats, which means variable-width codes up to 12 bits and the first\ntwo non-literal codes are a clear code and an EOF code.\n\nThe TIFF file format uses a similar but incompatible version of the LZW\nalgorithm. See the golang.org/x/image/tiff/lzw package for an\nimplementation.\n\n[\"compress/lzw\" on pkg.go.dev](https://pkg.go.dev/compress/lzw)", "url": "https://pkg.go.dev/compress/lzw", "path": "compress/lzw", "children": [] @@ -100,7 +136,7 @@ }, { "name": "list", - "synopsis": "Package list implements a doubly linked list.\n\nTo iterate over a list (where l is a *List):\n```\nfor e := l.Front(); e != nil; e = e.Next() {\n\t// do something with e.Value\n}\n\n[\"container/list\" on pkg.go.dev](https://pkg.go.dev/container/list)", + "synopsis": "Package list implements a doubly linked list.\n\nTo iterate over a list (where l is a *List):\n\n```\nfor e := l.Front(); e != nil; e = e.Next() {\n\t// do something with e.Value\n}\n\n[\"container/list\" on pkg.go.dev](https://pkg.go.dev/container/list)", "url": "https://pkg.go.dev/container/list", "path": "container/list", "children": [] @@ -116,7 +152,7 @@ }, { "name": "context", - "synopsis": "Package context defines the Context type, which carries deadlines,\ncancellation signals, and other request-scoped values across API boundaries\nand between processes.\n\nIncoming requests to a server should create a Context, and outgoing\ncalls to servers should accept a Context. The chain of function\ncalls between them must propagate the Context, optionally replacing\nit with a derived Context created using WithCancel, WithDeadline,\nWithTimeout, or WithValue. When a Context is canceled, all\nContexts derived from it are also canceled.\n\nThe WithCancel, WithDeadline, and WithTimeout functions take a\nContext (the parent) and return a derived Context (the child) and a\nCancelFunc. Calling the CancelFunc cancels the child and its\nchildren, removes the parent's reference to the child, and stops\nany associated timers. Failing to call the CancelFunc leaks the\nchild and its children until the parent is canceled or the timer\nfires. The go vet tool checks that CancelFuncs are used on all\ncontrol-flow paths.\n\nPrograms that use Contexts should follow these rules to keep interfaces\nconsistent across packages and enable static analysis tools to check context\npropagation:\n\nDo not store Contexts inside a struct type; instead, pass a Context\nexplicitly to each function that needs it. The Context should be the first\nparameter, typically named ctx:\n\n```\nfunc DoSomething(ctx context.Context, arg Arg) error {\n\t// ... use ctx ...\n}\n\n```\nDo not pass a nil Context, even if a function permits it. Pass context.TODO\nif you are unsure about which Context to use.\n\nUse context Values only for request-scoped data that transits processes and\nAPIs, not for passing optional parameters to functions.\n\nThe same Context may be passed to functions running in different goroutines;\nContexts are safe for simultaneous use by multiple goroutines.\n\nSee https://blog.golang.org/context for example code for a server that uses\nContexts.\n\n[\"context\" on pkg.go.dev](https://pkg.go.dev/context)", + "synopsis": "Package context defines the Context type, which carries deadlines,\ncancellation signals, and other request-scoped values across API boundaries\nand between processes.\n\nIncoming requests to a server should create a [Context], and outgoing\ncalls to servers should accept a Context. The chain of function\ncalls between them must propagate the Context, optionally replacing\nit with a derived Context created using [WithCancel], [WithDeadline],\n[WithTimeout], or [WithValue]. When a Context is canceled, all\nContexts derived from it are also canceled.\n\nThe [WithCancel], [WithDeadline], and [WithTimeout] functions take a\nContext (the parent) and return a derived Context (the child) and a\n[CancelFunc]. Calling the CancelFunc cancels the child and its\nchildren, removes the parent's reference to the child, and stops\nany associated timers. Failing to call the CancelFunc leaks the\nchild and its children until the parent is canceled or the timer\nfires. The go vet tool checks that CancelFuncs are used on all\ncontrol-flow paths.\n\nThe [WithCancelCause] function returns a [CancelCauseFunc], which\ntakes an error and records it as the cancellation cause. Calling\n[Cause] on the canceled context or any of its children retrieves\nthe cause. If no cause is specified, Cause(ctx) returns the same\nvalue as ctx.Err().\n\nPrograms that use Contexts should follow these rules to keep interfaces\nconsistent across packages and enable static analysis tools to check context\npropagation:\n\nDo not store Contexts inside a struct type; instead, pass a Context\nexplicitly to each function that needs it. The Context should be the first\nparameter, typically named ctx:\n\n```\nfunc DoSomething(ctx context.Context, arg Arg) error {\n\t// ... use ctx ...\n}\n\n```\nDo not pass a nil [Context], even if a function permits it. Pass [context.TODO]\nif you are unsure about which Context to use.\n\nUse context Values only for request-scoped data that transits processes and\nAPIs, not for passing optional parameters to functions.\n\nThe same Context may be passed to functions running in different goroutines;\nContexts are safe for simultaneous use by multiple goroutines.\n\nSee https://blog.golang.org/context for example code for a server that uses\nContexts.\n\n[\"context\" on pkg.go.dev](https://pkg.go.dev/context)", "url": "https://pkg.go.dev/context", "path": "context", "children": [] @@ -134,6 +170,13 @@ "path": "crypto/aes", "children": [] }, + { + "name": "boring", + "synopsis": "Package boring exposes functions that are only available when building with\nGo+BoringCrypto. This package is available on all targets as long as the\nGo+BoringCrypto toolchain is used. Use the Enabled function to determine\nwhether the BoringCrypto core is actually in use.\n\nAny time the Go+BoringCrypto toolchain is used, the \"boringcrypto\" build tag\nis satisfied, so that applications can tag files that use this package.\n\n[\"crypto/boring\" on pkg.go.dev](https://pkg.go.dev/crypto/boring)", + "url": "https://pkg.go.dev/crypto/boring", + "path": "crypto/boring", + "children": [] + }, { "name": "cipher", "synopsis": "Package cipher implements standard block cipher modes that can be wrapped\naround low-level block cipher implementations.\nSee https://csrc.nist.gov/groups/ST/toolkit/BCM/current_modes.html\nand NIST Special Publication 800-38A.\n\n[\"crypto/cipher\" on pkg.go.dev](https://pkg.go.dev/crypto/cipher)", @@ -155,6 +198,13 @@ "path": "crypto/dsa", "children": [] }, + { + "name": "ecdh", + "synopsis": "Package ecdh implements Elliptic Curve Diffie-Hellman over\nNIST curves and Curve25519.\n\n[\"crypto/ecdh\" on pkg.go.dev](https://pkg.go.dev/crypto/ecdh)", + "url": "https://pkg.go.dev/crypto/ecdh", + "path": "crypto/ecdh", + "children": [] + }, { "name": "ecdsa", "synopsis": "Package ecdsa implements the Elliptic Curve Digital Signature Algorithm, as\ndefined in FIPS 186-4 and SEC 1, Version 2.0.\n\nSignatures generated by this package are not deterministic, but entropy is\nmixed with the private key and the message, achieving the same level of\nsecurity in case of randomness source failure.\n\n[\"crypto/ecdsa\" on pkg.go.dev](https://pkg.go.dev/crypto/ecdsa)", @@ -171,7 +221,7 @@ }, { "name": "elliptic", - "synopsis": "Package elliptic implements the standard NIST P-224, P-256, P-384, and P-521\nelliptic curves over prime fields.\n\n[\"crypto/elliptic\" on pkg.go.dev](https://pkg.go.dev/crypto/elliptic)", + "synopsis": "Package elliptic implements the standard NIST P-224, P-256, P-384, and P-521\nelliptic curves over prime fields.\n\nDirect use of this package is deprecated, beyond the [P224], [P256], [P384],\nand [P521] values necessary to use [crypto/ecdsa]. Most other uses\nshould migrate to the more efficient and safer [crypto/ecdh], or to\nthird-party modules for lower-level functionality.\n\n[\"crypto/elliptic\" on pkg.go.dev](https://pkg.go.dev/crypto/elliptic)", "url": "https://pkg.go.dev/crypto/elliptic", "path": "crypto/elliptic", "children": [] @@ -206,7 +256,7 @@ }, { "name": "rsa", - "synopsis": "Package rsa implements RSA encryption as specified in PKCS #1 and RFC 8017.\n\nRSA is a single, fundamental operation that is used in this package to\nimplement either public-key encryption or public-key signatures.\n\nThe original specification for encryption and signatures with RSA is PKCS #1\nand the terms \"RSA encryption\" and \"RSA signatures\" by default refer to\nPKCS #1 version 1.5. However, that specification has flaws and new designs\nshould use version 2, usually called by just OAEP and PSS, where\npossible.\n\nTwo sets of interfaces are included in this package. When a more abstract\ninterface isn't necessary, there are functions for encrypting/decrypting\nwith v1.5/OAEP and signing/verifying with v1.5/PSS. If one needs to abstract\nover the public key primitive, the PrivateKey type implements the\nDecrypter and Signer interfaces from the crypto package.\n\nThe RSA operations in this package are not implemented using constant-time algorithms.\n\n[\"crypto/rsa\" on pkg.go.dev](https://pkg.go.dev/crypto/rsa)", + "synopsis": "Package rsa implements RSA encryption as specified in PKCS #1 and RFC 8017.\n\nRSA is a single, fundamental operation that is used in this package to\nimplement either public-key encryption or public-key signatures.\n\nThe original specification for encryption and signatures with RSA is PKCS #1\nand the terms \"RSA encryption\" and \"RSA signatures\" by default refer to\nPKCS #1 version 1.5. However, that specification has flaws and new designs\nshould use version 2, usually called by just OAEP and PSS, where\npossible.\n\nTwo sets of interfaces are included in this package. When a more abstract\ninterface isn't necessary, there are functions for encrypting/decrypting\nwith v1.5/OAEP and signing/verifying with v1.5/PSS. If one needs to abstract\nover the public key primitive, the PrivateKey type implements the\nDecrypter and Signer interfaces from the crypto package.\n\nOperations in this package are implemented using constant-time algorithms,\nexcept for [GenerateKey], [PrivateKey.Precompute], and [PrivateKey.Validate].\nEvery other operation only leaks the bit size of the involved values, which\nall depend on the selected key size.\n\n[\"crypto/rsa\" on pkg.go.dev](https://pkg.go.dev/crypto/rsa)", "url": "https://pkg.go.dev/crypto/rsa", "path": "crypto/rsa", "children": [] @@ -244,11 +294,19 @@ "synopsis": "Package tls partially implements TLS 1.2, as specified in RFC 5246,\nand TLS 1.3, as specified in RFC 8446.\n\n[\"crypto/tls\" on pkg.go.dev](https://pkg.go.dev/crypto/tls)", "url": "https://pkg.go.dev/crypto/tls", "path": "crypto/tls", - "children": [] + "children": [ + { + "name": "fipsonly", + "synopsis": "Package fipsonly restricts all TLS configuration to FIPS-approved settings.\n\nThe effect is triggered by importing the package anywhere in a program, as in:\n\n```\nimport _ \"crypto/tls/fipsonly\"\n\n```\nThis package only exists when using Go compiled with GOEXPERIMENT=boringcrypto.\n\n[\"crypto/tls/fipsonly\" on pkg.go.dev](https://pkg.go.dev/crypto/tls/fipsonly)", + "url": "https://pkg.go.dev/crypto/tls/fipsonly", + "path": "crypto/tls/fipsonly", + "children": [] + } + ] }, { "name": "x509", - "synopsis": "Copyright 2021 The Go Authors. All rights reserved.\nUse of this source code is governed by a BSD-style\nlicense that can be found in the LICENSE file.\n\nCopyright 2021 The Go Authors. All rights reserved.\nUse of this source code is governed by a BSD-style\nlicense that can be found in the LICENSE file.\n\nPackage x509 parses X.509-encoded keys and certificates.\n\n[\"crypto/x509\" on pkg.go.dev](https://pkg.go.dev/crypto/x509)", + "synopsis": "Package x509 implements a subset of the X.509 standard.\n\nIt allows parsing and generating certificates, certificate signing\nrequests, certificate revocation lists, and encoded public and private keys.\nIt provides a certificate verifier, complete with a chain builder.\n\nThe package targets the X.509 technical profile defined by the IETF (RFC\n2459/3280/5280), and as further restricted by the CA/Browser Forum Baseline\nRequirements. There is minimal support for features outside of these\nprofiles, as the primary goal of the package is to provide compatibility\nwith the publicly trusted TLS certificate ecosystem and its policies and\nconstraints.\n\nOn macOS and Windows, certificate verification is handled by system APIs, but\nthe package aims to apply consistent validation rules across operating\nsystems.\n\n[\"crypto/x509\" on pkg.go.dev](https://pkg.go.dev/crypto/x509)", "url": "https://pkg.go.dev/crypto/x509", "path": "crypto/x509", "children": [ @@ -301,14 +359,14 @@ }, { "name": "dwarf", - "synopsis": "Package dwarf provides access to DWARF debugging information loaded from\nexecutable files, as defined in the DWARF 2.0 Standard at\nhttp://dwarfstd.org/doc/dwarf-2.0.0.pdf\n\n[\"debug/dwarf\" on pkg.go.dev](https://pkg.go.dev/debug/dwarf)", + "synopsis": "Package dwarf provides access to DWARF debugging information loaded from\nexecutable files, as defined in the DWARF 2.0 Standard at\nhttp://dwarfstd.org/doc/dwarf-2.0.0.pdf.\n\n# Security\n\nThis package is not designed to be hardened against adversarial inputs, and is\noutside the scope of https://go.dev/security/policy. In particular, only basic\nvalidation is done when parsing object files. As such, care should be taken when\nparsing untrusted inputs, as parsing malformed files may consume significant\nresources, or cause panics.\n\n[\"debug/dwarf\" on pkg.go.dev](https://pkg.go.dev/debug/dwarf)", "url": "https://pkg.go.dev/debug/dwarf", "path": "debug/dwarf", "children": [] }, { "name": "elf", - "synopsis": "Package elf implements access to ELF object files.\n\n[\"debug/elf\" on pkg.go.dev](https://pkg.go.dev/debug/elf)", + "synopsis": "Package elf implements access to ELF object files.\n\n# Security\n\nThis package is not designed to be hardened against adversarial inputs, and is\noutside the scope of https://go.dev/security/policy. In particular, only basic\nvalidation is done when parsing object files. As such, care should be taken when\nparsing untrusted inputs, as parsing malformed files may consume significant\nresources, or cause panics.\n\n[\"debug/elf\" on pkg.go.dev](https://pkg.go.dev/debug/elf)", "url": "https://pkg.go.dev/debug/elf", "path": "debug/elf", "children": [] @@ -322,21 +380,21 @@ }, { "name": "macho", - "synopsis": "Package macho implements access to Mach-O object files.\n\n[\"debug/macho\" on pkg.go.dev](https://pkg.go.dev/debug/macho)", + "synopsis": "Package macho implements access to Mach-O object files.\n\n# Security\n\nThis package is not designed to be hardened against adversarial inputs, and is\noutside the scope of https://go.dev/security/policy. In particular, only basic\nvalidation is done when parsing object files. As such, care should be taken when\nparsing untrusted inputs, as parsing malformed files may consume significant\nresources, or cause panics.\n\n[\"debug/macho\" on pkg.go.dev](https://pkg.go.dev/debug/macho)", "url": "https://pkg.go.dev/debug/macho", "path": "debug/macho", "children": [] }, { "name": "pe", - "synopsis": "Package pe implements access to PE (Microsoft Windows Portable Executable) files.\n\n[\"debug/pe\" on pkg.go.dev](https://pkg.go.dev/debug/pe)", + "synopsis": "Package pe implements access to PE (Microsoft Windows Portable Executable) files.\n\n# Security\n\nThis package is not designed to be hardened against adversarial inputs, and is\noutside the scope of https://go.dev/security/policy. In particular, only basic\nvalidation is done when parsing object files. As such, care should be taken when\nparsing untrusted inputs, as parsing malformed files may consume significant\nresources, or cause panics.\n\n[\"debug/pe\" on pkg.go.dev](https://pkg.go.dev/debug/pe)", "url": "https://pkg.go.dev/debug/pe", "path": "debug/pe", "children": [] }, { "name": "plan9obj", - "synopsis": "Package plan9obj implements access to Plan 9 a.out object files.\n\n[\"debug/plan9obj\" on pkg.go.dev](https://pkg.go.dev/debug/plan9obj)", + "synopsis": "Package plan9obj implements access to Plan 9 a.out object files.\n\n# Security\n\nThis package is not designed to be hardened against adversarial inputs, and is\noutside the scope of https://go.dev/security/policy. In particular, only basic\nvalidation is done when parsing object files. As such, care should be taken when\nparsing untrusted inputs, as parsing malformed files may consume significant\nresources, or cause panics.\n\n[\"debug/plan9obj\" on pkg.go.dev](https://pkg.go.dev/debug/plan9obj)", "url": "https://pkg.go.dev/debug/plan9obj", "path": "debug/plan9obj", "children": [] @@ -345,14 +403,14 @@ }, { "name": "embed", - "synopsis": "Package embed provides access to files embedded in the running Go program.\n\nGo source files that import \"embed\" can use the //go:embed directive\nto initialize a variable of type string, []byte, or FS with the contents of\nfiles read from the package directory or subdirectories at compile time.\n\nFor example, here are three ways to embed a file named hello.txt\nand then print its contents at run time.\n\nEmbedding one file into a string:\n\n```\nimport _ \"embed\"\n\n//go:embed hello.txt\nvar s string\nprint(s)\n\n```\nEmbedding one file into a slice of bytes:\n\n```\nimport _ \"embed\"\n\n//go:embed hello.txt\nvar b []byte\nprint(string(b))\n\n```\nEmbedded one or more files into a file system:\n\n```\nimport \"embed\"\n\n//go:embed hello.txt\nvar f embed.FS\ndata, _ := f.ReadFile(\"hello.txt\")\nprint(string(data))\n\n```\nDirectives\n\nA //go:embed directive above a variable declaration specifies which files to embed,\nusing one or more path.Match patterns.\n\nThe directive must immediately precede a line containing the declaration of a single variable.\nOnly blank lines and ‘//’ line comments are permitted between the directive and the declaration.\n\nThe type of the variable must be a string type, or a slice of a byte type,\nor FS (or an alias of FS).\n\nFor example:\n\n```\npackage server\n\nimport \"embed\"\n\n// content holds our static web server content.\n//go:embed image/* template/*\n//go:embed html/index.html\nvar content embed.FS\n\n```\nThe Go build system will recognize the directives and arrange for the declared variable\n(in the example above, content) to be populated with the matching files from the file system.\n\nThe //go:embed directive accepts multiple space-separated patterns for\nbrevity, but it can also be repeated, to avoid very long lines when there are\nmany patterns. The patterns are interpreted relative to the package directory\ncontaining the source file. The path separator is a forward slash, even on\nWindows systems. Patterns may not contain ‘.’ or ‘..’ or empty path elements,\nnor may they begin or end with a slash. To match everything in the current\ndirectory, use ‘*’ instead of ‘.’. To allow for naming files with spaces in\ntheir names, patterns can be written as Go double-quoted or back-quoted\nstring literals.\n\nIf a pattern names a directory, all files in the subtree rooted at that directory are\nembedded (recursively), except that files with names beginning with ‘.’ or ‘_’\nare excluded. So the variable in the above example is almost equivalent to:\n\n```\n// content is our static web server content.\n//go:embed image template html/index.html\nvar content embed.FS\n\n```\nThe difference is that ‘image/*’ embeds ‘image/.tempfile’ while ‘image’ does not.\nNeither embeds ‘image/dir/.tempfile’.\n\nIf a pattern begins with the prefix ‘all:’, then the rule for walking directories is changed\nto include those files beginning with ‘.’ or ‘_’. For example, ‘all:image’ embeds\nboth ‘image/.tempfile’ and ‘image/dir/.tempfile’.\n\nThe //go:embed directive can be used with both exported and unexported variables,\ndepending on whether the package wants to make the data available to other packages.\nIt can only be used with variables at package scope, not with local variables.\n\nPatterns must not match files outside the package's module, such as ‘.git/*’ or symbolic links.\nMatches for empty directories are ignored. After that, each pattern in a //go:embed line\nmust match at least one file or non-empty directory.\n\nIf any patterns are invalid or have invalid matches, the build will fail.\n\nStrings and Bytes\n\nThe //go:embed line for a variable of type string or []byte can have only a single pattern,\nand that pattern can match only a single file. The string or []byte is initialized with\nthe contents of that file.\n\nThe //go:embed directive requires importing \"embed\", even when using a string or []byte.\nIn source files that don't refer to embed.FS, use a blank import (import _ \"embed\").\n\nFile Systems\n\nFor embedding a single file, a variable of type string or []byte is often best.\nThe FS type enables embedding a tree of files, such as a directory of static\nweb server content, as in the example above.\n\nFS implements the io/fs package's FS interface, so it can be used with any package that\nunderstands file systems, including net/http, text/template, and html/template.\n\nFor example, given the content variable in the example above, we can write:\n\n```\nhttp.Handle(\"/static/\", http.StripPrefix(\"/static/\", http.FileServer(http.FS(content))))\n\ntemplate.ParseFS(content, \"*.tmpl\")\n\n```\nTools\n\nTo support tools that analyze Go packages, the patterns found in //go:embed lines\nare available in “go list” output. See the EmbedPatterns, TestEmbedPatterns,\nand XTestEmbedPatterns fields in the “go help list” output.\n\n[\"embed\" on pkg.go.dev](https://pkg.go.dev/embed)", + "synopsis": "Package embed provides access to files embedded in the running Go program.\n\nGo source files that import \"embed\" can use the //go:embed directive\nto initialize a variable of type string, []byte, or FS with the contents of\nfiles read from the package directory or subdirectories at compile time.\n\nFor example, here are three ways to embed a file named hello.txt\nand then print its contents at run time.\n\nEmbedding one file into a string:\n\n```\nimport _ \"embed\"\n\n//go:embed hello.txt\nvar s string\nprint(s)\n\n```\nEmbedding one file into a slice of bytes:\n\n```\nimport _ \"embed\"\n\n//go:embed hello.txt\nvar b []byte\nprint(string(b))\n\n```\nEmbedded one or more files into a file system:\n\n```\nimport \"embed\"\n\n//go:embed hello.txt\nvar f embed.FS\ndata, _ := f.ReadFile(\"hello.txt\")\nprint(string(data))\n\n```\n# Directives\n\nA //go:embed directive above a variable declaration specifies which files to embed,\nusing one or more path.Match patterns.\n\nThe directive must immediately precede a line containing the declaration of a single variable.\nOnly blank lines and ‘//’ line comments are permitted between the directive and the declaration.\n\nThe type of the variable must be a string type, or a slice of a byte type,\nor FS (or an alias of FS).\n\nFor example:\n\n```\npackage server\n\nimport \"embed\"\n\n// content holds our static web server content.\n//go:embed image/* template/*\n//go:embed html/index.html\nvar content embed.FS\n\n```\nThe Go build system will recognize the directives and arrange for the declared variable\n(in the example above, content) to be populated with the matching files from the file system.\n\nThe //go:embed directive accepts multiple space-separated patterns for\nbrevity, but it can also be repeated, to avoid very long lines when there are\nmany patterns. The patterns are interpreted relative to the package directory\ncontaining the source file. The path separator is a forward slash, even on\nWindows systems. Patterns may not contain ‘.’ or ‘..’ or empty path elements,\nnor may they begin or end with a slash. To match everything in the current\ndirectory, use ‘*’ instead of ‘.’. To allow for naming files with spaces in\ntheir names, patterns can be written as Go double-quoted or back-quoted\nstring literals.\n\nIf a pattern names a directory, all files in the subtree rooted at that directory are\nembedded (recursively), except that files with names beginning with ‘.’ or ‘_’\nare excluded. So the variable in the above example is almost equivalent to:\n\n```\n// content is our static web server content.\n//go:embed image template html/index.html\nvar content embed.FS\n\n```\nThe difference is that ‘image/*’ embeds ‘image/.tempfile’ while ‘image’ does not.\nNeither embeds ‘image/dir/.tempfile’.\n\nIf a pattern begins with the prefix ‘all:’, then the rule for walking directories is changed\nto include those files beginning with ‘.’ or ‘_’. For example, ‘all:image’ embeds\nboth ‘image/.tempfile’ and ‘image/dir/.tempfile’.\n\nThe //go:embed directive can be used with both exported and unexported variables,\ndepending on whether the package wants to make the data available to other packages.\nIt can only be used with variables at package scope, not with local variables.\n\nPatterns must not match files outside the package's module, such as ‘.git/*’ or symbolic links.\nPatterns must not match files whose names include the special punctuation characters \" * \u003c \u003e ? ` ' | / \\ and :.\nMatches for empty directories are ignored. After that, each pattern in a //go:embed line\nmust match at least one file or non-empty directory.\n\nIf any patterns are invalid or have invalid matches, the build will fail.\n\n# Strings and Bytes\n\nThe //go:embed line for a variable of type string or []byte can have only a single pattern,\nand that pattern can match only a single file. The string or []byte is initialized with\nthe contents of that file.\n\nThe //go:embed directive requires importing \"embed\", even when using a string or []byte.\nIn source files that don't refer to embed.FS, use a blank import (import _ \"embed\").\n\n# File Systems\n\nFor embedding a single file, a variable of type string or []byte is often best.\nThe FS type enables embedding a tree of files, such as a directory of static\nweb server content, as in the example above.\n\nFS implements the io/fs package's FS interface, so it can be used with any package that\nunderstands file systems, including net/http, text/template, and html/template.\n\nFor example, given the content variable in the example above, we can write:\n\n```\nhttp.Handle(\"/static/\", http.StripPrefix(\"/static/\", http.FileServer(http.FS(content))))\n\ntemplate.ParseFS(content, \"*.tmpl\")\n\n```\n# Tools\n\nTo support tools that analyze Go packages, the patterns found in //go:embed lines\nare available in “go list” output. See the EmbedPatterns, TestEmbedPatterns,\nand XTestEmbedPatterns fields in the “go help list” output.\n\n[\"embed\" on pkg.go.dev](https://pkg.go.dev/embed)", "url": "https://pkg.go.dev/embed", "path": "embed", "children": [] }, { "name": "encoding", - "synopsis": "Package encoding defines interfaces shared by other packages that\nconvert data to and from byte-level and textual representations.\nPackages that check for these interfaces include encoding/gob,\nencoding/json, and encoding/xml. As a result, implementing an\ninterface once can make a type useful in multiple encodings.\nStandard types that implement these interfaces include time.Time and net.IP.\nThe interfaces come in pairs that produce and consume encoded data.\n\n[\"encoding\" on pkg.go.dev](https://pkg.go.dev/encoding)", + "synopsis": "Package encoding defines interfaces shared by other packages that\nconvert data to and from byte-level and textual representations.\nPackages that check for these interfaces include encoding/gob,\nencoding/json, and encoding/xml. As a result, implementing an\ninterface once can make a type useful in multiple encodings.\nStandard types that implement these interfaces include time.Time and net.IP.\nThe interfaces come in pairs that produce and consume encoded data.\n\nAdding encoding/decoding methods to existing types may constitute a breaking change,\nas they can be used for serialization in communicating with programs\nwritten with different library versions.\nThe policy for packages maintained by the Go project is to only allow\nthe addition of marshaling functions if no existing, reasonable marshaling exists.\n\n[\"encoding\" on pkg.go.dev](https://pkg.go.dev/encoding)", "url": "https://pkg.go.dev/encoding", "path": "encoding", "children": [ @@ -365,7 +423,7 @@ }, { "name": "asn1", - "synopsis": "Package asn1 implements parsing of DER-encoded ASN.1 data structures,\nas defined in ITU-T Rec X.690.\n\nSee also ``A Layman's Guide to a Subset of ASN.1, BER, and DER,''\nhttp://luca.ntop.org/Teaching/Appunti/asn1.html.\n\n[\"encoding/asn1\" on pkg.go.dev](https://pkg.go.dev/encoding/asn1)", + "synopsis": "Package asn1 implements parsing of DER-encoded ASN.1 data structures,\nas defined in ITU-T Rec X.690.\n\nSee also “A Layman's Guide to a Subset of ASN.1, BER, and DER,”\nhttp://luca.ntop.org/Teaching/Appunti/asn1.html.\n\n[\"encoding/asn1\" on pkg.go.dev](https://pkg.go.dev/encoding/asn1)", "url": "https://pkg.go.dev/encoding/asn1", "path": "encoding/asn1", "children": [] @@ -400,7 +458,7 @@ }, { "name": "gob", - "synopsis": "Package gob manages streams of gobs - binary values exchanged between an\nEncoder (transmitter) and a Decoder (receiver). A typical use is transporting\narguments and results of remote procedure calls (RPCs) such as those provided by\npackage \"net/rpc\".\n\nThe implementation compiles a custom codec for each data type in the stream and\nis most efficient when a single Encoder is used to transmit a stream of values,\namortizing the cost of compilation.\n\nBasics\n\nA stream of gobs is self-describing. Each data item in the stream is preceded by\na specification of its type, expressed in terms of a small set of predefined\ntypes. Pointers are not transmitted, but the things they point to are\ntransmitted; that is, the values are flattened. Nil pointers are not permitted,\nas they have no value. Recursive types work fine, but\nrecursive values (data with cycles) are problematic. This may change.\n\nTo use gobs, create an Encoder and present it with a series of data items as\nvalues or addresses that can be dereferenced to values. The Encoder makes sure\nall type information is sent before it is needed. At the receive side, a\nDecoder retrieves values from the encoded stream and unpacks them into local\nvariables.\n\nTypes and Values\n\nThe source and destination values/types need not correspond exactly. For structs,\nfields (identified by name) that are in the source but absent from the receiving\nvariable will be ignored. Fields that are in the receiving variable but missing\nfrom the transmitted type or value will be ignored in the destination. If a field\nwith the same name is present in both, their types must be compatible. Both the\nreceiver and transmitter will do all necessary indirection and dereferencing to\nconvert between gobs and actual Go values. For instance, a gob type that is\nschematically,\n\n```\nstruct { A, B int }\n\n```\ncan be sent from or received into any of these Go types:\n\n```\nstruct { A, B int }\t// the same\n*struct { A, B int }\t// extra indirection of the struct\nstruct { *A, **B int }\t// extra indirection of the fields\nstruct { A, B int64 }\t// different concrete value type; see below\n\n```\nIt may also be received into any of these:\n\n```\nstruct { A, B int }\t// the same\nstruct { B, A int }\t// ordering doesn't matter; matching is by name\nstruct { A, B, C int }\t// extra field (C) ignored\nstruct { B int }\t// missing field (A) ignored; data will be dropped\nstruct { B, C int }\t// missing field (A) ignored; extra field (C) ignored.\n\n```\nAttempting to receive into these types will draw a decode error:\n\n```\nstruct { A int; B uint }\t// change of signedness for B\nstruct { A int; B float }\t// change of type for B\nstruct { }\t\t\t// no field names in common\nstruct { C, D int }\t\t// no field names in common\n\n```\nIntegers are transmitted two ways: arbitrary precision signed integers or\narbitrary precision unsigned integers. There is no int8, int16 etc.\ndiscrimination in the gob format; there are only signed and unsigned integers. As\ndescribed below, the transmitter sends the value in a variable-length encoding;\nthe receiver accepts the value and stores it in the destination variable.\nFloating-point numbers are always sent using IEEE-754 64-bit precision (see\nbelow).\n\nSigned integers may be received into any signed integer variable: int, int16, etc.;\nunsigned integers may be received into any unsigned integer variable; and floating\npoint values may be received into any floating point variable. However,\nthe destination variable must be able to represent the value or the decode\noperation will fail.\n\nStructs, arrays and slices are also supported. Structs encode and decode only\nexported fields. Strings and arrays of bytes are supported with a special,\nefficient representation (see below). When a slice is decoded, if the existing\nslice has capacity the slice will be extended in place; if not, a new array is\nallocated. Regardless, the length of the resulting slice reports the number of\nelements decoded.\n\nIn general, if allocation is required, the decoder will allocate memory. If not,\nit will update the destination variables with values read from the stream. It does\nnot initialize them first, so if the destination is a compound value such as a\nmap, struct, or slice, the decoded values will be merged elementwise into the\nexisting variables.\n\nFunctions and channels will not be sent in a gob. Attempting to encode such a value\nat the top level will fail. A struct field of chan or func type is treated exactly\nlike an unexported field and is ignored.\n\nGob can encode a value of any type implementing the GobEncoder or\nencoding.BinaryMarshaler interfaces by calling the corresponding method,\nin that order of preference.\n\nGob can decode a value of any type implementing the GobDecoder or\nencoding.BinaryUnmarshaler interfaces by calling the corresponding method,\nagain in that order of preference.\n\nEncoding Details\n\nThis section documents the encoding, details that are not important for most\nusers. Details are presented bottom-up.\n\nAn unsigned integer is sent one of two ways. If it is less than 128, it is sent\nas a byte with that value. Otherwise it is sent as a minimal-length big-endian\n(high byte first) byte stream holding the value, preceded by one byte holding the\nbyte count, negated. Thus 0 is transmitted as (00), 7 is transmitted as (07) and\n256 is transmitted as (FE 01 00).\n\nA boolean is encoded within an unsigned integer: 0 for false, 1 for true.\n\nA signed integer, i, is encoded within an unsigned integer, u. Within u, bits 1\nupward contain the value; bit 0 says whether they should be complemented upon\nreceipt. The encode algorithm looks like this:\n\n```\nvar u uint\nif i \u003c 0 {\n\tu = (^uint(i) \u003c\u003c 1) | 1 // complement i, bit 0 is 1\n} else {\n\tu = (uint(i) \u003c\u003c 1) // do not complement i, bit 0 is 0\n}\nencodeUnsigned(u)\n\n```\nThe low bit is therefore analogous to a sign bit, but making it the complement bit\ninstead guarantees that the largest negative integer is not a special case. For\nexample, -129=^128=(^256\u003e\u003e1) encodes as (FE 01 01).\n\nFloating-point numbers are always sent as a representation of a float64 value.\nThat value is converted to a uint64 using math.Float64bits. The uint64 is then\nbyte-reversed and sent as a regular unsigned integer. The byte-reversal means the\nexponent and high-precision part of the mantissa go first. Since the low bits are\noften zero, this can save encoding bytes. For instance, 17.0 is encoded in only\nthree bytes (FE 31 40).\n\nStrings and slices of bytes are sent as an unsigned count followed by that many\nuninterpreted bytes of the value.\n\nAll other slices and arrays are sent as an unsigned count followed by that many\nelements using the standard gob encoding for their type, recursively.\n\nMaps are sent as an unsigned count followed by that many key, element\npairs. Empty but non-nil maps are sent, so if the receiver has not allocated\none already, one will always be allocated on receipt unless the transmitted map\nis nil and not at the top level.\n\nIn slices and arrays, as well as maps, all elements, even zero-valued elements,\nare transmitted, even if all the elements are zero.\n\nStructs are sent as a sequence of (field number, field value) pairs. The field\nvalue is sent using the standard gob encoding for its type, recursively. If a\nfield has the zero value for its type (except for arrays; see above), it is omitted\nfrom the transmission. The field number is defined by the type of the encoded\nstruct: the first field of the encoded type is field 0, the second is field 1,\netc. When encoding a value, the field numbers are delta encoded for efficiency\nand the fields are always sent in order of increasing field number; the deltas are\ntherefore unsigned. The initialization for the delta encoding sets the field\nnumber to -1, so an unsigned integer field 0 with value 7 is transmitted as unsigned\ndelta = 1, unsigned value = 7 or (01 07). Finally, after all the fields have been\nsent a terminating mark denotes the end of the struct. That mark is a delta=0\nvalue, which has representation (00).\n\nInterface types are not checked for compatibility; all interface types are\ntreated, for transmission, as members of a single \"interface\" type, analogous to\nint or []byte - in effect they're all treated as interface{}. Interface values\nare transmitted as a string identifying the concrete type being sent (a name\nthat must be pre-defined by calling Register), followed by a byte count of the\nlength of the following data (so the value can be skipped if it cannot be\nstored), followed by the usual encoding of concrete (dynamic) value stored in\nthe interface value. (A nil interface value is identified by the empty string\nand transmits no value.) Upon receipt, the decoder verifies that the unpacked\nconcrete item satisfies the interface of the receiving variable.\n\nIf a value is passed to Encode and the type is not a struct (or pointer to struct,\netc.), for simplicity of processing it is represented as a struct of one field.\nThe only visible effect of this is to encode a zero byte after the value, just as\nafter the last field of an encoded struct, so that the decode algorithm knows when\nthe top-level value is complete.\n\nThe representation of types is described below. When a type is defined on a given\nconnection between an Encoder and Decoder, it is assigned a signed integer type\nid. When Encoder.Encode(v) is called, it makes sure there is an id assigned for\nthe type of v and all its elements and then it sends the pair (typeid, encoded-v)\nwhere typeid is the type id of the encoded type of v and encoded-v is the gob\nencoding of the value v.\n\nTo define a type, the encoder chooses an unused, positive type id and sends the\npair (-type id, encoded-type) where encoded-type is the gob encoding of a wireType\ndescription, constructed from these types:\n\n```\ntype wireType struct {\n\tArrayT *ArrayType\n\tSliceT *SliceType\n\tStructT *StructType\n\tMapT *MapType\n\tGobEncoderT *gobEncoderType\n\tBinaryMarshalerT *gobEncoderType\n\tTextMarshalerT *gobEncoderType\n\n}\ntype arrayType struct {\n\tCommonType\n\tElem typeId\n\tLen int\n}\ntype CommonType struct {\n\tName string // the name of the struct type\n\tId int // the id of the type, repeated so it's inside the type\n}\ntype sliceType struct {\n\tCommonType\n\tElem typeId\n}\ntype structType struct {\n\tCommonType\n\tField []*fieldType // the fields of the struct.\n}\ntype fieldType struct {\n\tName string // the name of the field.\n\tId int // the type id of the field, which must be already defined\n}\ntype mapType struct {\n\tCommonType\n\tKey typeId\n\tElem typeId\n}\ntype gobEncoderType struct {\n\tCommonType\n}\n\n```\nIf there are nested type ids, the types for all inner type ids must be defined\nbefore the top-level type id is used to describe an encoded-v.\n\nFor simplicity in setup, the connection is defined to understand these types a\npriori, as well as the basic gob types int, uint, etc. Their ids are:\n\n```\nbool 1\nint 2\nuint 3\nfloat 4\n[]byte 5\nstring 6\ncomplex 7\ninterface 8\n// gap for reserved ids.\nWireType 16\nArrayType 17\nCommonType 18\nSliceType 19\nStructType 20\nFieldType 21\n// 22 is slice of fieldType.\nMapType 23\n\n```\nFinally, each message created by a call to Encode is preceded by an encoded\nunsigned integer count of the number of bytes remaining in the message. After\nthe initial type name, interface values are wrapped the same way; in effect, the\ninterface value acts like a recursive invocation of Encode.\n\nIn summary, a gob stream looks like\n\n```\n(byteCount (-type id, encoding of a wireType)* (type id, encoding of a value))*\n\n```\nwhere * signifies zero or more repetitions and the type id of a value must\nbe predefined or be defined before the value in the stream.\n\nCompatibility: Any future changes to the package will endeavor to maintain\ncompatibility with streams encoded using previous versions. That is, any released\nversion of this package should be able to decode data written with any previously\nreleased version, subject to issues such as security fixes. See the Go compatibility\ndocument for background: https://golang.org/doc/go1compat\n\nSee \"Gobs of data\" for a design discussion of the gob wire format:\nhttps://blog.golang.org/gobs-of-data\n\n[\"encoding/gob\" on pkg.go.dev](https://pkg.go.dev/encoding/gob)", + "synopsis": "Package gob manages streams of gobs - binary values exchanged between an\nEncoder (transmitter) and a Decoder (receiver). A typical use is transporting\narguments and results of remote procedure calls (RPCs) such as those provided by\n[net/rpc].\n\nThe implementation compiles a custom codec for each data type in the stream and\nis most efficient when a single Encoder is used to transmit a stream of values,\namortizing the cost of compilation.\n\n# Basics\n\nA stream of gobs is self-describing. Each data item in the stream is preceded by\na specification of its type, expressed in terms of a small set of predefined\ntypes. Pointers are not transmitted, but the things they point to are\ntransmitted; that is, the values are flattened. Nil pointers are not permitted,\nas they have no value. Recursive types work fine, but\nrecursive values (data with cycles) are problematic. This may change.\n\nTo use gobs, create an Encoder and present it with a series of data items as\nvalues or addresses that can be dereferenced to values. The Encoder makes sure\nall type information is sent before it is needed. At the receive side, a\nDecoder retrieves values from the encoded stream and unpacks them into local\nvariables.\n\n# Types and Values\n\nThe source and destination values/types need not correspond exactly. For structs,\nfields (identified by name) that are in the source but absent from the receiving\nvariable will be ignored. Fields that are in the receiving variable but missing\nfrom the transmitted type or value will be ignored in the destination. If a field\nwith the same name is present in both, their types must be compatible. Both the\nreceiver and transmitter will do all necessary indirection and dereferencing to\nconvert between gobs and actual Go values. For instance, a gob type that is\nschematically,\n\n```\nstruct { A, B int }\n\n```\ncan be sent from or received into any of these Go types:\n\n```\nstruct { A, B int }\t// the same\n*struct { A, B int }\t// extra indirection of the struct\nstruct { *A, **B int }\t// extra indirection of the fields\nstruct { A, B int64 }\t// different concrete value type; see below\n\n```\nIt may also be received into any of these:\n\n```\nstruct { A, B int }\t// the same\nstruct { B, A int }\t// ordering doesn't matter; matching is by name\nstruct { A, B, C int }\t// extra field (C) ignored\nstruct { B int }\t// missing field (A) ignored; data will be dropped\nstruct { B, C int }\t// missing field (A) ignored; extra field (C) ignored.\n\n```\nAttempting to receive into these types will draw a decode error:\n\n```\nstruct { A int; B uint }\t// change of signedness for B\nstruct { A int; B float }\t// change of type for B\nstruct { }\t\t\t// no field names in common\nstruct { C, D int }\t\t// no field names in common\n\n```\nIntegers are transmitted two ways: arbitrary precision signed integers or\narbitrary precision unsigned integers. There is no int8, int16 etc.\ndiscrimination in the gob format; there are only signed and unsigned integers. As\ndescribed below, the transmitter sends the value in a variable-length encoding;\nthe receiver accepts the value and stores it in the destination variable.\nFloating-point numbers are always sent using IEEE-754 64-bit precision (see\nbelow).\n\nSigned integers may be received into any signed integer variable: int, int16, etc.;\nunsigned integers may be received into any unsigned integer variable; and floating\npoint values may be received into any floating point variable. However,\nthe destination variable must be able to represent the value or the decode\noperation will fail.\n\nStructs, arrays and slices are also supported. Structs encode and decode only\nexported fields. Strings and arrays of bytes are supported with a special,\nefficient representation (see below). When a slice is decoded, if the existing\nslice has capacity the slice will be extended in place; if not, a new array is\nallocated. Regardless, the length of the resulting slice reports the number of\nelements decoded.\n\nIn general, if allocation is required, the decoder will allocate memory. If not,\nit will update the destination variables with values read from the stream. It does\nnot initialize them first, so if the destination is a compound value such as a\nmap, struct, or slice, the decoded values will be merged elementwise into the\nexisting variables.\n\nFunctions and channels will not be sent in a gob. Attempting to encode such a value\nat the top level will fail. A struct field of chan or func type is treated exactly\nlike an unexported field and is ignored.\n\nGob can encode a value of any type implementing the GobEncoder or\nencoding.BinaryMarshaler interfaces by calling the corresponding method,\nin that order of preference.\n\nGob can decode a value of any type implementing the GobDecoder or\nencoding.BinaryUnmarshaler interfaces by calling the corresponding method,\nagain in that order of preference.\n\n# Encoding Details\n\nThis section documents the encoding, details that are not important for most\nusers. Details are presented bottom-up.\n\nAn unsigned integer is sent one of two ways. If it is less than 128, it is sent\nas a byte with that value. Otherwise it is sent as a minimal-length big-endian\n(high byte first) byte stream holding the value, preceded by one byte holding the\nbyte count, negated. Thus 0 is transmitted as (00), 7 is transmitted as (07) and\n256 is transmitted as (FE 01 00).\n\nA boolean is encoded within an unsigned integer: 0 for false, 1 for true.\n\nA signed integer, i, is encoded within an unsigned integer, u. Within u, bits 1\nupward contain the value; bit 0 says whether they should be complemented upon\nreceipt. The encode algorithm looks like this:\n\n```\nvar u uint\nif i \u003c 0 {\n\tu = (^uint(i) \u003c\u003c 1) | 1 // complement i, bit 0 is 1\n} else {\n\tu = (uint(i) \u003c\u003c 1) // do not complement i, bit 0 is 0\n}\nencodeUnsigned(u)\n\n```\nThe low bit is therefore analogous to a sign bit, but making it the complement bit\ninstead guarantees that the largest negative integer is not a special case. For\nexample, -129=^128=(^256\u003e\u003e1) encodes as (FE 01 01).\n\nFloating-point numbers are always sent as a representation of a float64 value.\nThat value is converted to a uint64 using math.Float64bits. The uint64 is then\nbyte-reversed and sent as a regular unsigned integer. The byte-reversal means the\nexponent and high-precision part of the mantissa go first. Since the low bits are\noften zero, this can save encoding bytes. For instance, 17.0 is encoded in only\nthree bytes (FE 31 40).\n\nStrings and slices of bytes are sent as an unsigned count followed by that many\nuninterpreted bytes of the value.\n\nAll other slices and arrays are sent as an unsigned count followed by that many\nelements using the standard gob encoding for their type, recursively.\n\nMaps are sent as an unsigned count followed by that many key, element\npairs. Empty but non-nil maps are sent, so if the receiver has not allocated\none already, one will always be allocated on receipt unless the transmitted map\nis nil and not at the top level.\n\nIn slices and arrays, as well as maps, all elements, even zero-valued elements,\nare transmitted, even if all the elements are zero.\n\nStructs are sent as a sequence of (field number, field value) pairs. The field\nvalue is sent using the standard gob encoding for its type, recursively. If a\nfield has the zero value for its type (except for arrays; see above), it is omitted\nfrom the transmission. The field number is defined by the type of the encoded\nstruct: the first field of the encoded type is field 0, the second is field 1,\netc. When encoding a value, the field numbers are delta encoded for efficiency\nand the fields are always sent in order of increasing field number; the deltas are\ntherefore unsigned. The initialization for the delta encoding sets the field\nnumber to -1, so an unsigned integer field 0 with value 7 is transmitted as unsigned\ndelta = 1, unsigned value = 7 or (01 07). Finally, after all the fields have been\nsent a terminating mark denotes the end of the struct. That mark is a delta=0\nvalue, which has representation (00).\n\nInterface types are not checked for compatibility; all interface types are\ntreated, for transmission, as members of a single \"interface\" type, analogous to\nint or []byte - in effect they're all treated as interface{}. Interface values\nare transmitted as a string identifying the concrete type being sent (a name\nthat must be pre-defined by calling Register), followed by a byte count of the\nlength of the following data (so the value can be skipped if it cannot be\nstored), followed by the usual encoding of concrete (dynamic) value stored in\nthe interface value. (A nil interface value is identified by the empty string\nand transmits no value.) Upon receipt, the decoder verifies that the unpacked\nconcrete item satisfies the interface of the receiving variable.\n\nIf a value is passed to Encode and the type is not a struct (or pointer to struct,\netc.), for simplicity of processing it is represented as a struct of one field.\nThe only visible effect of this is to encode a zero byte after the value, just as\nafter the last field of an encoded struct, so that the decode algorithm knows when\nthe top-level value is complete.\n\nThe representation of types is described below. When a type is defined on a given\nconnection between an Encoder and Decoder, it is assigned a signed integer type\nid. When Encoder.Encode(v) is called, it makes sure there is an id assigned for\nthe type of v and all its elements and then it sends the pair (typeid, encoded-v)\nwhere typeid is the type id of the encoded type of v and encoded-v is the gob\nencoding of the value v.\n\nTo define a type, the encoder chooses an unused, positive type id and sends the\npair (-type id, encoded-type) where encoded-type is the gob encoding of a wireType\ndescription, constructed from these types:\n\n```\ntype wireType struct {\n\tArrayT *ArrayType\n\tSliceT *SliceType\n\tStructT *StructType\n\tMapT *MapType\n\tGobEncoderT *gobEncoderType\n\tBinaryMarshalerT *gobEncoderType\n\tTextMarshalerT *gobEncoderType\n\n}\ntype arrayType struct {\n\tCommonType\n\tElem typeId\n\tLen int\n}\ntype CommonType struct {\n\tName string // the name of the struct type\n\tId int // the id of the type, repeated so it's inside the type\n}\ntype sliceType struct {\n\tCommonType\n\tElem typeId\n}\ntype structType struct {\n\tCommonType\n\tField []*fieldType // the fields of the struct.\n}\ntype fieldType struct {\n\tName string // the name of the field.\n\tId int // the type id of the field, which must be already defined\n}\ntype mapType struct {\n\tCommonType\n\tKey typeId\n\tElem typeId\n}\ntype gobEncoderType struct {\n\tCommonType\n}\n\n```\nIf there are nested type ids, the types for all inner type ids must be defined\nbefore the top-level type id is used to describe an encoded-v.\n\nFor simplicity in setup, the connection is defined to understand these types a\npriori, as well as the basic gob types int, uint, etc. Their ids are:\n\n```\nbool 1\nint 2\nuint 3\nfloat 4\n[]byte 5\nstring 6\ncomplex 7\ninterface 8\n// gap for reserved ids.\nWireType 16\nArrayType 17\nCommonType 18\nSliceType 19\nStructType 20\nFieldType 21\n// 22 is slice of fieldType.\nMapType 23\n\n```\nFinally, each message created by a call to Encode is preceded by an encoded\nunsigned integer count of the number of bytes remaining in the message. After\nthe initial type name, interface values are wrapped the same way; in effect, the\ninterface value acts like a recursive invocation of Encode.\n\nIn summary, a gob stream looks like\n\n```\n(byteCount (-type id, encoding of a wireType)* (type id, encoding of a value))*\n\n```\nwhere * signifies zero or more repetitions and the type id of a value must\nbe predefined or be defined before the value in the stream.\n\nCompatibility: Any future changes to the package will endeavor to maintain\ncompatibility with streams encoded using previous versions. That is, any released\nversion of this package should be able to decode data written with any previously\nreleased version, subject to issues such as security fixes. See the Go compatibility\ndocument for background: https://golang.org/doc/go1compat\n\nSee \"Gobs of data\" for a design discussion of the gob wire format:\nhttps://blog.golang.org/gobs-of-data\n\n# Security\n\nThis package is not designed to be hardened against adversarial inputs, and is\noutside the scope of https://go.dev/security/policy. In particular, the Decoder\ndoes only basic sanity checking on decoded input sizes, and its limits are not\nconfigurable. Care should be taken when decoding gob data from untrusted\nsources, which may consume significant resources.\n\n[\"encoding/gob\" on pkg.go.dev](https://pkg.go.dev/encoding/gob)", "url": "https://pkg.go.dev/encoding/gob", "path": "encoding/gob", "children": [] @@ -437,28 +495,28 @@ }, { "name": "errors", - "synopsis": "Package errors implements functions to manipulate errors.\n\nThe New function creates errors whose only content is a text message.\n\nThe Unwrap, Is and As functions work on errors that may wrap other errors.\nAn error wraps another error if its type has the method\n\n```\nUnwrap() error\n\n```\nIf e.Unwrap() returns a non-nil error w, then we say that e wraps w.\n\nUnwrap unpacks wrapped errors. If its argument's type has an\nUnwrap method, it calls the method once. Otherwise, it returns nil.\n\nA simple way to create wrapped errors is to call fmt.Errorf and apply the %w verb\nto the error argument:\n\n```\nerrors.Unwrap(fmt.Errorf(\"... %w ...\", ..., err, ...))\n\n```\nreturns err.\n\nIs unwraps its first argument sequentially looking for an error that matches the\nsecond. It reports whether it finds a match. It should be used in preference to\nsimple equality checks:\n\n```\nif errors.Is(err, fs.ErrExist)\n\n```\nis preferable to\n\n```\nif err == fs.ErrExist\n\n```\nbecause the former will succeed if err wraps fs.ErrExist.\n\nAs unwraps its first argument sequentially looking for an error that can be\nassigned to its second argument, which must be a pointer. If it succeeds, it\nperforms the assignment and returns true. Otherwise, it returns false. The form\n\n```\nvar perr *fs.PathError\nif errors.As(err, \u0026perr) {\n\tfmt.Println(perr.Path)\n}\n\n```\nis preferable to\n\n```\nif perr, ok := err.(*fs.PathError); ok {\n\tfmt.Println(perr.Path)\n}\n\n```\nbecause the former will succeed if err wraps an *fs.PathError.\n\n[\"errors\" on pkg.go.dev](https://pkg.go.dev/errors)", + "synopsis": "Package errors implements functions to manipulate errors.\n\nThe [New] function creates errors whose only content is a text message.\n\nAn error e wraps another error if e's type has one of the methods\n\n```\nUnwrap() error\nUnwrap() []error\n\n```\nIf e.Unwrap() returns a non-nil error w or a slice containing w,\nthen we say that e wraps w. A nil error returned from e.Unwrap()\nindicates that e does not wrap any error. It is invalid for an\nUnwrap method to return an []error containing a nil error value.\n\nAn easy way to create wrapped errors is to call [fmt.Errorf] and apply\nthe %w verb to the error argument:\n\n```\nwrapsErr := fmt.Errorf(\"... %w ...\", ..., err, ...)\n\n```\nSuccessive unwrapping of an error creates a tree. The [Is] and [As]\nfunctions inspect an error's tree by examining first the error\nitself followed by the tree of each of its children in turn\n(pre-order, depth-first traversal).\n\nIs examines the tree of its first argument looking for an error that\nmatches the second. It reports whether it finds a match. It should be\nused in preference to simple equality checks:\n\n```\nif errors.Is(err, fs.ErrExist)\n\n```\nis preferable to\n\n```\nif err == fs.ErrExist\n\n```\nbecause the former will succeed if err wraps [io/fs.ErrExist].\n\nAs examines the tree of its first argument looking for an error that can be\nassigned to its second argument, which must be a pointer. If it succeeds, it\nperforms the assignment and returns true. Otherwise, it returns false. The form\n\n```\nvar perr *fs.PathError\nif errors.As(err, \u0026perr) {\n\tfmt.Println(perr.Path)\n}\n\n```\nis preferable to\n\n```\nif perr, ok := err.(*fs.PathError); ok {\n\tfmt.Println(perr.Path)\n}\n\n```\nbecause the former will succeed if err wraps an [*io/fs.PathError].\n\n[\"errors\" on pkg.go.dev](https://pkg.go.dev/errors)", "url": "https://pkg.go.dev/errors", "path": "errors", "children": [] }, { "name": "expvar", - "synopsis": "Package expvar provides a standardized interface to public variables, such\nas operation counters in servers. It exposes these variables via HTTP at\n/debug/vars in JSON format.\n\nOperations to set or modify these public variables are atomic.\n\nIn addition to adding the HTTP handler, this package registers the\nfollowing variables:\n\n```\ncmdline os.Args\nmemstats runtime.Memstats\n\n```\nThe package is sometimes only imported for the side effect of\nregistering its HTTP handler and the above variables. To use it\nthis way, link this package into your program:\n```\nimport _ \"expvar\"\n\n[\"expvar\" on pkg.go.dev](https://pkg.go.dev/expvar)", + "synopsis": "Package expvar provides a standardized interface to public variables, such\nas operation counters in servers. It exposes these variables via HTTP at\n/debug/vars in JSON format.\n\nOperations to set or modify these public variables are atomic.\n\nIn addition to adding the HTTP handler, this package registers the\nfollowing variables:\n\n```\ncmdline os.Args\nmemstats runtime.Memstats\n\n```\nThe package is sometimes only imported for the side effect of\nregistering its HTTP handler and the above variables. To use it\nthis way, link this package into your program:\n\n```\nimport _ \"expvar\"\n\n[\"expvar\" on pkg.go.dev](https://pkg.go.dev/expvar)", "url": "https://pkg.go.dev/expvar", "path": "expvar", "children": [] }, { "name": "flag", - "synopsis": "```\nPackage flag implements command-line flag parsing.\n\nUsage\n\nDefine flags using flag.String(), Bool(), Int(), etc.\n\nThis declares an integer flag, -n, stored in the pointer nFlag, with type *int:\n\timport \"flag\"\n\tvar nFlag = flag.Int(\"n\", 1234, \"help message for flag n\")\nIf you like, you can bind the flag to a variable using the Var() functions.\n\tvar flagvar int\n\tfunc init() {\n\t\tflag.IntVar(\u0026flagvar, \"flagname\", 1234, \"help message for flagname\")\n\t}\nOr you can create custom flags that satisfy the Value interface (with\npointer receivers) and couple them to flag parsing by\n\tflag.Var(\u0026flagVal, \"name\", \"help message for flagname\")\nFor such flags, the default value is just the initial value of the variable.\n\nAfter all flags are defined, call\n\tflag.Parse()\nto parse the command line into the defined flags.\n\nFlags may then be used directly. If you're using the flags themselves,\nthey are all pointers; if you bind to variables, they're values.\n\tfmt.Println(\"ip has value \", *ip)\n\tfmt.Println(\"flagvar has value \", flagvar)\n\nAfter parsing, the arguments following the flags are available as the\nslice flag.Args() or individually as flag.Arg(i).\nThe arguments are indexed from 0 through flag.NArg()-1.\n\nCommand line flag syntax\n\nThe following forms are permitted:\n\n\t-flag\n\t-flag=x\n\t-flag x // non-boolean flags only\nOne or two minus signs may be used; they are equivalent.\nThe last form is not permitted for boolean flags because the\nmeaning of the command\n\tcmd -x *\nwhere * is a Unix shell wildcard, will change if there is a file\ncalled 0, false, etc. You must use the -flag=false form to turn\noff a boolean flag.\n\nFlag parsing stops just before the first non-flag argument\n(\"-\" is a non-flag argument) or after the terminator \"--\".\n\nInteger flags accept 1234, 0664, 0x1234 and may be negative.\nBoolean flags may be:\n\t1, 0, t, f, T, F, true, false, TRUE, FALSE, True, False\nDuration flags accept any input valid for time.ParseDuration.\n\nThe default set of command-line flags is controlled by\ntop-level functions. The FlagSet type allows one to define\nindependent sets of flags, such as to implement subcommands\nin a command-line interface. The methods of FlagSet are\nanalogous to the top-level functions for the command-line\nflag set.\n\n[\"flag\" on pkg.go.dev](https://pkg.go.dev/flag)", + "synopsis": "Package flag implements command-line flag parsing.\n\n# Usage\n\nDefine flags using flag.String(), Bool(), Int(), etc.\n\nThis declares an integer flag, -n, stored in the pointer nFlag, with type *int:\n\n```\nimport \"flag\"\nvar nFlag = flag.Int(\"n\", 1234, \"help message for flag n\")\n\n```\nIf you like, you can bind the flag to a variable using the Var() functions.\n\n```\nvar flagvar int\nfunc init() {\n\tflag.IntVar(\u0026flagvar, \"flagname\", 1234, \"help message for flagname\")\n}\n\n```\nOr you can create custom flags that satisfy the Value interface (with\npointer receivers) and couple them to flag parsing by\n\n```\nflag.Var(\u0026flagVal, \"name\", \"help message for flagname\")\n\n```\nFor such flags, the default value is just the initial value of the variable.\n\nAfter all flags are defined, call\n\n```\nflag.Parse()\n\n```\nto parse the command line into the defined flags.\n\nFlags may then be used directly. If you're using the flags themselves,\nthey are all pointers; if you bind to variables, they're values.\n\n```\nfmt.Println(\"ip has value \", *ip)\nfmt.Println(\"flagvar has value \", flagvar)\n\n```\nAfter parsing, the arguments following the flags are available as the\nslice flag.Args() or individually as flag.Arg(i).\nThe arguments are indexed from 0 through flag.NArg()-1.\n\n# Command line flag syntax\n\nThe following forms are permitted:\n\n```\n-flag\n--flag // double dashes are also permitted\n-flag=x\n-flag x // non-boolean flags only\n\n```\nOne or two dashes may be used; they are equivalent.\nThe last form is not permitted for boolean flags because the\nmeaning of the command\n\n```\ncmd -x *\n\n```\nwhere * is a Unix shell wildcard, will change if there is a file\ncalled 0, false, etc. You must use the -flag=false form to turn\noff a boolean flag.\n\nFlag parsing stops just before the first non-flag argument\n(\"-\" is a non-flag argument) or after the terminator \"--\".\n\nInteger flags accept 1234, 0664, 0x1234 and may be negative.\nBoolean flags may be:\n\n```\n1, 0, t, f, T, F, true, false, TRUE, FALSE, True, False\n\n```\nDuration flags accept any input valid for time.ParseDuration.\n\nThe default set of command-line flags is controlled by\ntop-level functions. The FlagSet type allows one to define\nindependent sets of flags, such as to implement subcommands\nin a command-line interface. The methods of FlagSet are\nanalogous to the top-level functions for the command-line\nflag set.\n\n[\"flag\" on pkg.go.dev](https://pkg.go.dev/flag)", "url": "https://pkg.go.dev/flag", "path": "flag", "children": [] }, { "name": "fmt", - "synopsis": "```\nPackage fmt implements formatted I/O with functions analogous\nto C's printf and scanf. The format 'verbs' are derived from C's but\nare simpler.\n\nPrinting\n\nThe verbs:\n\nGeneral:\n\t%v\tthe value in a default format\n\t\twhen printing structs, the plus flag (%+v) adds field names\n\t%#v\ta Go-syntax representation of the value\n\t%T\ta Go-syntax representation of the type of the value\n\t%%\ta literal percent sign; consumes no value\n\nBoolean:\n\t%t\tthe word true or false\nInteger:\n\t%b\tbase 2\n\t%c\tthe character represented by the corresponding Unicode code point\n\t%d\tbase 10\n\t%o\tbase 8\n\t%O\tbase 8 with 0o prefix\n\t%q\ta single-quoted character literal safely escaped with Go syntax.\n\t%x\tbase 16, with lower-case letters for a-f\n\t%X\tbase 16, with upper-case letters for A-F\n\t%U\tUnicode format: U+1234; same as \"U+%04X\"\nFloating-point and complex constituents:\n\t%b\tdecimalless scientific notation with exponent a power of two,\n\t\tin the manner of strconv.FormatFloat with the 'b' format,\n\t\te.g. -123456p-78\n\t%e\tscientific notation, e.g. -1.234456e+78\n\t%E\tscientific notation, e.g. -1.234456E+78\n\t%f\tdecimal point but no exponent, e.g. 123.456\n\t%F\tsynonym for %f\n\t%g\t%e for large exponents, %f otherwise. Precision is discussed below.\n\t%G\t%E for large exponents, %F otherwise\n\t%x\thexadecimal notation (with decimal power of two exponent), e.g. -0x1.23abcp+20\n\t%X\tupper-case hexadecimal notation, e.g. -0X1.23ABCP+20\nString and slice of bytes (treated equivalently with these verbs):\n\t%s\tthe uninterpreted bytes of the string or slice\n\t%q\ta double-quoted string safely escaped with Go syntax\n\t%x\tbase 16, lower-case, two characters per byte\n\t%X\tbase 16, upper-case, two characters per byte\nSlice:\n\t%p\taddress of 0th element in base 16 notation, with leading 0x\nPointer:\n\t%p\tbase 16 notation, with leading 0x\n\tThe %b, %d, %o, %x and %X verbs also work with pointers,\n\tformatting the value exactly as if it were an integer.\n\nThe default format for %v is:\n\tbool: %t\n\tint, int8 etc.: %d\n\tuint, uint8 etc.: %d, %#x if printed with %#v\n\tfloat32, complex64, etc: %g\n\tstring: %s\n\tchan: %p\n\tpointer: %p\nFor compound objects, the elements are printed using these rules, recursively,\nlaid out like this:\n\tstruct: {field0 field1 ...}\n\tarray, slice: [elem0 elem1 ...]\n\tmaps: map[key1:value1 key2:value2 ...]\n\tpointer to above: \u0026{}, \u0026[], \u0026map[]\n\nWidth is specified by an optional decimal number immediately preceding the verb.\nIf absent, the width is whatever is necessary to represent the value.\nPrecision is specified after the (optional) width by a period followed by a\ndecimal number. If no period is present, a default precision is used.\nA period with no following number specifies a precision of zero.\nExamples:\n\t%f default width, default precision\n\t%9f width 9, default precision\n\t%.2f default width, precision 2\n\t%9.2f width 9, precision 2\n\t%9.f width 9, precision 0\n\nWidth and precision are measured in units of Unicode code points,\nthat is, runes. (This differs from C's printf where the\nunits are always measured in bytes.) Either or both of the flags\nmay be replaced with the character '*', causing their values to be\nobtained from the next operand (preceding the one to format),\nwhich must be of type int.\n\nFor most values, width is the minimum number of runes to output,\npadding the formatted form with spaces if necessary.\n\nFor strings, byte slices and byte arrays, however, precision\nlimits the length of the input to be formatted (not the size of\nthe output), truncating if necessary. Normally it is measured in\nrunes, but for these types when formatted with the %x or %X format\nit is measured in bytes.\n\nFor floating-point values, width sets the minimum width of the field and\nprecision sets the number of places after the decimal, if appropriate,\nexcept that for %g/%G precision sets the maximum number of significant\ndigits (trailing zeros are removed). For example, given 12.345 the format\n%6.3f prints 12.345 while %.3g prints 12.3. The default precision for %e, %f\nand %#g is 6; for %g it is the smallest number of digits necessary to identify\nthe value uniquely.\n\nFor complex numbers, the width and precision apply to the two\ncomponents independently and the result is parenthesized, so %f applied\nto 1.2+3.4i produces (1.200000+3.400000i).\n\nOther flags:\n\t+\talways print a sign for numeric values;\n\t\tguarantee ASCII-only output for %q (%+q)\n\t-\tpad with spaces on the right rather than the left (left-justify the field)\n\t#\talternate format: add leading 0b for binary (%#b), 0 for octal (%#o),\n\t\t0x or 0X for hex (%#x or %#X); suppress 0x for %p (%#p);\n\t\tfor %q, print a raw (backquoted) string if strconv.CanBackquote\n\t\treturns true;\n\t\talways print a decimal point for %e, %E, %f, %F, %g and %G;\n\t\tdo not remove trailing zeros for %g and %G;\n\t\twrite e.g. U+0078 'x' if the character is printable for %U (%#U).\n\t' '\t(space) leave a space for elided sign in numbers (% d);\n\t\tput spaces between bytes printing strings or slices in hex (% x, % X)\n\t0\tpad with leading zeros rather than spaces;\n\t\tfor numbers, this moves the padding after the sign\n\nFlags are ignored by verbs that do not expect them.\nFor example there is no alternate decimal format, so %#d and %d\nbehave identically.\n\nFor each Printf-like function, there is also a Print function\nthat takes no format and is equivalent to saying %v for every\noperand. Another variant Println inserts blanks between\noperands and appends a newline.\n\nRegardless of the verb, if an operand is an interface value,\nthe internal concrete value is used, not the interface itself.\nThus:\n\tvar i interface{} = 23\n\tfmt.Printf(\"%v\\n\", i)\nwill print 23.\n\nExcept when printed using the verbs %T and %p, special\nformatting considerations apply for operands that implement\ncertain interfaces. In order of application:\n\n1. If the operand is a reflect.Value, the operand is replaced by the\nconcrete value that it holds, and printing continues with the next rule.\n\n2. If an operand implements the Formatter interface, it will\nbe invoked. In this case the interpretation of verbs and flags is\ncontrolled by that implementation.\n\n3. If the %v verb is used with the # flag (%#v) and the operand\nimplements the GoStringer interface, that will be invoked.\n\nIf the format (which is implicitly %v for Println etc.) is valid\nfor a string (%s %q %v %x %X), the following two rules apply:\n\n4. If an operand implements the error interface, the Error method\nwill be invoked to convert the object to a string, which will then\nbe formatted as required by the verb (if any).\n\n5. If an operand implements method String() string, that method\nwill be invoked to convert the object to a string, which will then\nbe formatted as required by the verb (if any).\n\nFor compound operands such as slices and structs, the format\napplies to the elements of each operand, recursively, not to the\noperand as a whole. Thus %q will quote each element of a slice\nof strings, and %6.2f will control formatting for each element\nof a floating-point array.\n\nHowever, when printing a byte slice with a string-like verb\n(%s %q %x %X), it is treated identically to a string, as a single item.\n\nTo avoid recursion in cases such as\n\ttype X string\n\tfunc (x X) String() string { return Sprintf(\"\u003c%s\u003e\", x) }\nconvert the value before recurring:\n\tfunc (x X) String() string { return Sprintf(\"\u003c%s\u003e\", string(x)) }\nInfinite recursion can also be triggered by self-referential data\nstructures, such as a slice that contains itself as an element, if\nthat type has a String method. Such pathologies are rare, however,\nand the package does not protect against them.\n\nWhen printing a struct, fmt cannot and therefore does not invoke\nformatting methods such as Error or String on unexported fields.\n\nExplicit argument indexes\n\nIn Printf, Sprintf, and Fprintf, the default behavior is for each\nformatting verb to format successive arguments passed in the call.\nHowever, the notation [n] immediately before the verb indicates that the\nnth one-indexed argument is to be formatted instead. The same notation\nbefore a '*' for a width or precision selects the argument index holding\nthe value. After processing a bracketed expression [n], subsequent verbs\nwill use arguments n+1, n+2, etc. unless otherwise directed.\n\nFor example,\n\tfmt.Sprintf(\"%[2]d %[1]d\\n\", 11, 22)\nwill yield \"22 11\", while\n\tfmt.Sprintf(\"%[3]*.[2]*[1]f\", 12.0, 2, 6)\nequivalent to\n\tfmt.Sprintf(\"%6.2f\", 12.0)\nwill yield \" 12.00\". Because an explicit index affects subsequent verbs,\nthis notation can be used to print the same values multiple times\nby resetting the index for the first argument to be repeated:\n\tfmt.Sprintf(\"%d %d %#[1]x %#x\", 16, 17)\nwill yield \"16 17 0x10 0x11\".\n\nFormat errors\n\nIf an invalid argument is given for a verb, such as providing\na string to %d, the generated string will contain a\ndescription of the problem, as in these examples:\n\n\tWrong type or unknown verb: %!verb(type=value)\n\t\tPrintf(\"%d\", \"hi\"): %!d(string=hi)\n\tToo many arguments: %!(EXTRA type=value)\n\t\tPrintf(\"hi\", \"guys\"): hi%!(EXTRA string=guys)\n\tToo few arguments: %!verb(MISSING)\n\t\tPrintf(\"hi%d\"): hi%!d(MISSING)\n\tNon-int for width or precision: %!(BADWIDTH) or %!(BADPREC)\n\t\tPrintf(\"%*s\", 4.5, \"hi\"): %!(BADWIDTH)hi\n\t\tPrintf(\"%.*s\", 4.5, \"hi\"): %!(BADPREC)hi\n\tInvalid or invalid use of argument index: %!(BADINDEX)\n\t\tPrintf(\"%*[2]d\", 7): %!d(BADINDEX)\n\t\tPrintf(\"%.[2]d\", 7): %!d(BADINDEX)\n\nAll errors begin with the string \"%!\" followed sometimes\nby a single character (the verb) and end with a parenthesized\ndescription.\n\nIf an Error or String method triggers a panic when called by a\nprint routine, the fmt package reformats the error message\nfrom the panic, decorating it with an indication that it came\nthrough the fmt package. For example, if a String method\ncalls panic(\"bad\"), the resulting formatted message will look\nlike\n\t%!s(PANIC=bad)\n\nThe %!s just shows the print verb in use when the failure\noccurred. If the panic is caused by a nil receiver to an Error\nor String method, however, the output is the undecorated\nstring, \"\u003cnil\u003e\".\n\nScanning\n\nAn analogous set of functions scans formatted text to yield\nvalues. Scan, Scanf and Scanln read from os.Stdin; Fscan,\nFscanf and Fscanln read from a specified io.Reader; Sscan,\nSscanf and Sscanln read from an argument string.\n\nScan, Fscan, Sscan treat newlines in the input as spaces.\n\nScanln, Fscanln and Sscanln stop scanning at a newline and\nrequire that the items be followed by a newline or EOF.\n\nScanf, Fscanf, and Sscanf parse the arguments according to a\nformat string, analogous to that of Printf. In the text that\nfollows, 'space' means any Unicode whitespace character\nexcept newline.\n\nIn the format string, a verb introduced by the % character\nconsumes and parses input; these verbs are described in more\ndetail below. A character other than %, space, or newline in\nthe format consumes exactly that input character, which must\nbe present. A newline with zero or more spaces before it in\nthe format string consumes zero or more spaces in the input\nfollowed by a single newline or the end of the input. A space\nfollowing a newline in the format string consumes zero or more\nspaces in the input. Otherwise, any run of one or more spaces\nin the format string consumes as many spaces as possible in\nthe input. Unless the run of spaces in the format string\nappears adjacent to a newline, the run must consume at least\none space from the input or find the end of the input.\n\nThe handling of spaces and newlines differs from that of C's\nscanf family: in C, newlines are treated as any other space,\nand it is never an error when a run of spaces in the format\nstring finds no spaces to consume in the input.\n\nThe verbs behave analogously to those of Printf.\nFor example, %x will scan an integer as a hexadecimal number,\nand %v will scan the default representation format for the value.\nThe Printf verbs %p and %T and the flags # and + are not implemented.\nFor floating-point and complex values, all valid formatting verbs\n(%b %e %E %f %F %g %G %x %X and %v) are equivalent and accept\nboth decimal and hexadecimal notation (for example: \"2.3e+7\", \"0x4.5p-8\")\nand digit-separating underscores (for example: \"3.14159_26535_89793\").\n\nInput processed by verbs is implicitly space-delimited: the\nimplementation of every verb except %c starts by discarding\nleading spaces from the remaining input, and the %s verb\n(and %v reading into a string) stops consuming input at the first\nspace or newline character.\n\nThe familiar base-setting prefixes 0b (binary), 0o and 0 (octal),\nand 0x (hexadecimal) are accepted when scanning integers\nwithout a format or with the %v verb, as are digit-separating\nunderscores.\n\nWidth is interpreted in the input text but there is no\nsyntax for scanning with a precision (no %5.2f, just %5f).\nIf width is provided, it applies after leading spaces are\ntrimmed and specifies the maximum number of runes to read\nto satisfy the verb. For example,\n Sscanf(\" 1234567 \", \"%5s%d\", \u0026s, \u0026i)\nwill set s to \"12345\" and i to 67 while\n Sscanf(\" 12 34 567 \", \"%5s%d\", \u0026s, \u0026i)\nwill set s to \"12\" and i to 34.\n\nIn all the scanning functions, a carriage return followed\nimmediately by a newline is treated as a plain newline\n(\\r\\n means the same as \\n).\n\nIn all the scanning functions, if an operand implements method\nScan (that is, it implements the Scanner interface) that\nmethod will be used to scan the text for that operand. Also,\nif the number of arguments scanned is less than the number of\narguments provided, an error is returned.\n\nAll arguments to be scanned must be either pointers to basic\ntypes or implementations of the Scanner interface.\n\nLike Scanf and Fscanf, Sscanf need not consume its entire input.\nThere is no way to recover how much of the input string Sscanf used.\n\nNote: Fscan etc. can read one character (rune) past the input\nthey return, which means that a loop calling a scan routine\nmay skip some of the input. This is usually a problem only\nwhen there is no space between input values. If the reader\nprovided to Fscan implements ReadRune, that method will be used\nto read characters. If the reader also implements UnreadRune,\nthat method will be used to save the character and successive\ncalls will not lose data. To attach ReadRune and UnreadRune\nmethods to a reader without that capability, use\nbufio.NewReader.\n\n[\"fmt\" on pkg.go.dev](https://pkg.go.dev/fmt)", + "synopsis": "Package fmt implements formatted I/O with functions analogous\nto C's printf and scanf. The format 'verbs' are derived from C's but\nare simpler.\n\n# Printing\n\nThe verbs:\n\nGeneral:\n\n```\n%v\tthe value in a default format\n\twhen printing structs, the plus flag (%+v) adds field names\n%#v\ta Go-syntax representation of the value\n%T\ta Go-syntax representation of the type of the value\n%%\ta literal percent sign; consumes no value\n\n```\nBoolean:\n\n```\n%t\tthe word true or false\n\n```\nInteger:\n\n```\n%b\tbase 2\n%c\tthe character represented by the corresponding Unicode code point\n%d\tbase 10\n%o\tbase 8\n%O\tbase 8 with 0o prefix\n%q\ta single-quoted character literal safely escaped with Go syntax.\n%x\tbase 16, with lower-case letters for a-f\n%X\tbase 16, with upper-case letters for A-F\n%U\tUnicode format: U+1234; same as \"U+%04X\"\n\n```\nFloating-point and complex constituents:\n\n```\n%b\tdecimalless scientific notation with exponent a power of two,\n\tin the manner of strconv.FormatFloat with the 'b' format,\n\te.g. -123456p-78\n%e\tscientific notation, e.g. -1.234456e+78\n%E\tscientific notation, e.g. -1.234456E+78\n%f\tdecimal point but no exponent, e.g. 123.456\n%F\tsynonym for %f\n%g\t%e for large exponents, %f otherwise. Precision is discussed below.\n%G\t%E for large exponents, %F otherwise\n%x\thexadecimal notation (with decimal power of two exponent), e.g. -0x1.23abcp+20\n%X\tupper-case hexadecimal notation, e.g. -0X1.23ABCP+20\n\n```\nString and slice of bytes (treated equivalently with these verbs):\n\n```\n%s\tthe uninterpreted bytes of the string or slice\n%q\ta double-quoted string safely escaped with Go syntax\n%x\tbase 16, lower-case, two characters per byte\n%X\tbase 16, upper-case, two characters per byte\n\n```\nSlice:\n\n```\n%p\taddress of 0th element in base 16 notation, with leading 0x\n\n```\nPointer:\n\n```\n%p\tbase 16 notation, with leading 0x\nThe %b, %d, %o, %x and %X verbs also work with pointers,\nformatting the value exactly as if it were an integer.\n\n```\nThe default format for %v is:\n\n```\nbool: %t\nint, int8 etc.: %d\nuint, uint8 etc.: %d, %#x if printed with %#v\nfloat32, complex64, etc: %g\nstring: %s\nchan: %p\npointer: %p\n\n```\nFor compound objects, the elements are printed using these rules, recursively,\nlaid out like this:\n\n```\nstruct: {field0 field1 ...}\narray, slice: [elem0 elem1 ...]\nmaps: map[key1:value1 key2:value2 ...]\npointer to above: \u0026{}, \u0026[], \u0026map[]\n\n```\nWidth is specified by an optional decimal number immediately preceding the verb.\nIf absent, the width is whatever is necessary to represent the value.\nPrecision is specified after the (optional) width by a period followed by a\ndecimal number. If no period is present, a default precision is used.\nA period with no following number specifies a precision of zero.\nExamples:\n\n```\n%f default width, default precision\n%9f width 9, default precision\n%.2f default width, precision 2\n%9.2f width 9, precision 2\n%9.f width 9, precision 0\n\n```\nWidth and precision are measured in units of Unicode code points,\nthat is, runes. (This differs from C's printf where the\nunits are always measured in bytes.) Either or both of the flags\nmay be replaced with the character '*', causing their values to be\nobtained from the next operand (preceding the one to format),\nwhich must be of type int.\n\nFor most values, width is the minimum number of runes to output,\npadding the formatted form with spaces if necessary.\n\nFor strings, byte slices and byte arrays, however, precision\nlimits the length of the input to be formatted (not the size of\nthe output), truncating if necessary. Normally it is measured in\nrunes, but for these types when formatted with the %x or %X format\nit is measured in bytes.\n\nFor floating-point values, width sets the minimum width of the field and\nprecision sets the number of places after the decimal, if appropriate,\nexcept that for %g/%G precision sets the maximum number of significant\ndigits (trailing zeros are removed). For example, given 12.345 the format\n%6.3f prints 12.345 while %.3g prints 12.3. The default precision for %e, %f\nand %#g is 6; for %g it is the smallest number of digits necessary to identify\nthe value uniquely.\n\nFor complex numbers, the width and precision apply to the two\ncomponents independently and the result is parenthesized, so %f applied\nto 1.2+3.4i produces (1.200000+3.400000i).\n\nWhen formatting a single integer code point or a rune string (type []rune)\nwith %q, invalid Unicode code points are changed to the Unicode replacement\ncharacter, U+FFFD, as in strconv.QuoteRune.\n\nOther flags:\n\n```\n'+'\talways print a sign for numeric values;\n\tguarantee ASCII-only output for %q (%+q)\n'-'\tpad with spaces on the right rather than the left (left-justify the field)\n'#'\talternate format: add leading 0b for binary (%#b), 0 for octal (%#o),\n\t0x or 0X for hex (%#x or %#X); suppress 0x for %p (%#p);\n\tfor %q, print a raw (backquoted) string if strconv.CanBackquote\n\treturns true;\n\talways print a decimal point for %e, %E, %f, %F, %g and %G;\n\tdo not remove trailing zeros for %g and %G;\n\twrite e.g. U+0078 'x' if the character is printable for %U (%#U).\n' '\t(space) leave a space for elided sign in numbers (% d);\n\tput spaces between bytes printing strings or slices in hex (% x, % X)\n'0'\tpad with leading zeros rather than spaces;\n\tfor numbers, this moves the padding after the sign;\n\tignored for strings, byte slices and byte arrays\n\n```\nFlags are ignored by verbs that do not expect them.\nFor example there is no alternate decimal format, so %#d and %d\nbehave identically.\n\nFor each Printf-like function, there is also a Print function\nthat takes no format and is equivalent to saying %v for every\noperand. Another variant Println inserts blanks between\noperands and appends a newline.\n\nRegardless of the verb, if an operand is an interface value,\nthe internal concrete value is used, not the interface itself.\nThus:\n\n```\nvar i interface{} = 23\nfmt.Printf(\"%v\\n\", i)\n\n```\nwill print 23.\n\nExcept when printed using the verbs %T and %p, special\nformatting considerations apply for operands that implement\ncertain interfaces. In order of application:\n\n1. If the operand is a reflect.Value, the operand is replaced by the\nconcrete value that it holds, and printing continues with the next rule.\n\n2. If an operand implements the Formatter interface, it will\nbe invoked. In this case the interpretation of verbs and flags is\ncontrolled by that implementation.\n\n3. If the %v verb is used with the # flag (%#v) and the operand\nimplements the GoStringer interface, that will be invoked.\n\nIf the format (which is implicitly %v for Println etc.) is valid\nfor a string (%s %q %v %x %X), the following two rules apply:\n\n4. If an operand implements the error interface, the Error method\nwill be invoked to convert the object to a string, which will then\nbe formatted as required by the verb (if any).\n\n5. If an operand implements method String() string, that method\nwill be invoked to convert the object to a string, which will then\nbe formatted as required by the verb (if any).\n\nFor compound operands such as slices and structs, the format\napplies to the elements of each operand, recursively, not to the\noperand as a whole. Thus %q will quote each element of a slice\nof strings, and %6.2f will control formatting for each element\nof a floating-point array.\n\nHowever, when printing a byte slice with a string-like verb\n(%s %q %x %X), it is treated identically to a string, as a single item.\n\nTo avoid recursion in cases such as\n\n```\ntype X string\nfunc (x X) String() string { return Sprintf(\"\u003c%s\u003e\", x) }\n\n```\nconvert the value before recurring:\n\n```\nfunc (x X) String() string { return Sprintf(\"\u003c%s\u003e\", string(x)) }\n\n```\nInfinite recursion can also be triggered by self-referential data\nstructures, such as a slice that contains itself as an element, if\nthat type has a String method. Such pathologies are rare, however,\nand the package does not protect against them.\n\nWhen printing a struct, fmt cannot and therefore does not invoke\nformatting methods such as Error or String on unexported fields.\n\n# Explicit argument indexes\n\nIn Printf, Sprintf, and Fprintf, the default behavior is for each\nformatting verb to format successive arguments passed in the call.\nHowever, the notation [n] immediately before the verb indicates that the\nnth one-indexed argument is to be formatted instead. The same notation\nbefore a '*' for a width or precision selects the argument index holding\nthe value. After processing a bracketed expression [n], subsequent verbs\nwill use arguments n+1, n+2, etc. unless otherwise directed.\n\nFor example,\n\n```\nfmt.Sprintf(\"%[2]d %[1]d\\n\", 11, 22)\n\n```\nwill yield \"22 11\", while\n\n```\nfmt.Sprintf(\"%[3]*.[2]*[1]f\", 12.0, 2, 6)\n\n```\nequivalent to\n\n```\nfmt.Sprintf(\"%6.2f\", 12.0)\n\n```\nwill yield \" 12.00\". Because an explicit index affects subsequent verbs,\nthis notation can be used to print the same values multiple times\nby resetting the index for the first argument to be repeated:\n\n```\nfmt.Sprintf(\"%d %d %#[1]x %#x\", 16, 17)\n\n```\nwill yield \"16 17 0x10 0x11\".\n\n# Format errors\n\nIf an invalid argument is given for a verb, such as providing\na string to %d, the generated string will contain a\ndescription of the problem, as in these examples:\n\n```\nWrong type or unknown verb: %!verb(type=value)\n\tPrintf(\"%d\", \"hi\"): %!d(string=hi)\nToo many arguments: %!(EXTRA type=value)\n\tPrintf(\"hi\", \"guys\"): hi%!(EXTRA string=guys)\nToo few arguments: %!verb(MISSING)\n\tPrintf(\"hi%d\"): hi%!d(MISSING)\nNon-int for width or precision: %!(BADWIDTH) or %!(BADPREC)\n\tPrintf(\"%*s\", 4.5, \"hi\"): %!(BADWIDTH)hi\n\tPrintf(\"%.*s\", 4.5, \"hi\"): %!(BADPREC)hi\nInvalid or invalid use of argument index: %!(BADINDEX)\n\tPrintf(\"%*[2]d\", 7): %!d(BADINDEX)\n\tPrintf(\"%.[2]d\", 7): %!d(BADINDEX)\n\n```\nAll errors begin with the string \"%!\" followed sometimes\nby a single character (the verb) and end with a parenthesized\ndescription.\n\nIf an Error or String method triggers a panic when called by a\nprint routine, the fmt package reformats the error message\nfrom the panic, decorating it with an indication that it came\nthrough the fmt package. For example, if a String method\ncalls panic(\"bad\"), the resulting formatted message will look\nlike\n\n```\n%!s(PANIC=bad)\n\n```\nThe %!s just shows the print verb in use when the failure\noccurred. If the panic is caused by a nil receiver to an Error\nor String method, however, the output is the undecorated\nstring, \"\u003cnil\u003e\".\n\n# Scanning\n\nAn analogous set of functions scans formatted text to yield\nvalues. Scan, Scanf and Scanln read from os.Stdin; Fscan,\nFscanf and Fscanln read from a specified io.Reader; Sscan,\nSscanf and Sscanln read from an argument string.\n\nScan, Fscan, Sscan treat newlines in the input as spaces.\n\nScanln, Fscanln and Sscanln stop scanning at a newline and\nrequire that the items be followed by a newline or EOF.\n\nScanf, Fscanf, and Sscanf parse the arguments according to a\nformat string, analogous to that of Printf. In the text that\nfollows, 'space' means any Unicode whitespace character\nexcept newline.\n\nIn the format string, a verb introduced by the % character\nconsumes and parses input; these verbs are described in more\ndetail below. A character other than %, space, or newline in\nthe format consumes exactly that input character, which must\nbe present. A newline with zero or more spaces before it in\nthe format string consumes zero or more spaces in the input\nfollowed by a single newline or the end of the input. A space\nfollowing a newline in the format string consumes zero or more\nspaces in the input. Otherwise, any run of one or more spaces\nin the format string consumes as many spaces as possible in\nthe input. Unless the run of spaces in the format string\nappears adjacent to a newline, the run must consume at least\none space from the input or find the end of the input.\n\nThe handling of spaces and newlines differs from that of C's\nscanf family: in C, newlines are treated as any other space,\nand it is never an error when a run of spaces in the format\nstring finds no spaces to consume in the input.\n\nThe verbs behave analogously to those of Printf.\nFor example, %x will scan an integer as a hexadecimal number,\nand %v will scan the default representation format for the value.\nThe Printf verbs %p and %T and the flags # and + are not implemented.\nFor floating-point and complex values, all valid formatting verbs\n(%b %e %E %f %F %g %G %x %X and %v) are equivalent and accept\nboth decimal and hexadecimal notation (for example: \"2.3e+7\", \"0x4.5p-8\")\nand digit-separating underscores (for example: \"3.14159_26535_89793\").\n\nInput processed by verbs is implicitly space-delimited: the\nimplementation of every verb except %c starts by discarding\nleading spaces from the remaining input, and the %s verb\n(and %v reading into a string) stops consuming input at the first\nspace or newline character.\n\nThe familiar base-setting prefixes 0b (binary), 0o and 0 (octal),\nand 0x (hexadecimal) are accepted when scanning integers\nwithout a format or with the %v verb, as are digit-separating\nunderscores.\n\nWidth is interpreted in the input text but there is no\nsyntax for scanning with a precision (no %5.2f, just %5f).\nIf width is provided, it applies after leading spaces are\ntrimmed and specifies the maximum number of runes to read\nto satisfy the verb. For example,\n\n```\nSscanf(\" 1234567 \", \"%5s%d\", \u0026s, \u0026i)\n\n```\nwill set s to \"12345\" and i to 67 while\n\n```\nSscanf(\" 12 34 567 \", \"%5s%d\", \u0026s, \u0026i)\n\n```\nwill set s to \"12\" and i to 34.\n\nIn all the scanning functions, a carriage return followed\nimmediately by a newline is treated as a plain newline\n(\\r\\n means the same as \\n).\n\nIn all the scanning functions, if an operand implements method\nScan (that is, it implements the Scanner interface) that\nmethod will be used to scan the text for that operand. Also,\nif the number of arguments scanned is less than the number of\narguments provided, an error is returned.\n\nAll arguments to be scanned must be either pointers to basic\ntypes or implementations of the Scanner interface.\n\nLike Scanf and Fscanf, Sscanf need not consume its entire input.\nThere is no way to recover how much of the input string Sscanf used.\n\nNote: Fscan etc. can read one character (rune) past the input\nthey return, which means that a loop calling a scan routine\nmay skip some of the input. This is usually a problem only\nwhen there is no space between input values. If the reader\nprovided to Fscan implements ReadRune, that method will be used\nto read characters. If the reader also implements UnreadRune,\nthat method will be used to save the character and successive\ncalls will not lose data. To attach ReadRune and UnreadRune\nmethods to a reader without that capability, use\nbufio.NewReader.\n\n[\"fmt\" on pkg.go.dev](https://pkg.go.dev/fmt)", "url": "https://pkg.go.dev/fmt", "path": "fmt", "children": [] @@ -478,13 +536,13 @@ }, { "name": "build", - "synopsis": "Package build gathers information about Go packages.\n\nGo Path\n\nThe Go path is a list of directory trees containing Go source code.\nIt is consulted to resolve imports that cannot be found in the standard\nGo tree. The default path is the value of the GOPATH environment\nvariable, interpreted as a path list appropriate to the operating system\n(on Unix, the variable is a colon-separated string;\non Windows, a semicolon-separated string;\non Plan 9, a list).\n\nEach directory listed in the Go path must have a prescribed structure:\n\nThe src/ directory holds source code. The path below 'src' determines\nthe import path or executable name.\n\nThe pkg/ directory holds installed package objects.\nAs in the Go tree, each target operating system and\narchitecture pair has its own subdirectory of pkg\n(pkg/GOOS_GOARCH).\n\nIf DIR is a directory listed in the Go path, a package with\nsource in DIR/src/foo/bar can be imported as \"foo/bar\" and\nhas its compiled form installed to \"DIR/pkg/GOOS_GOARCH/foo/bar.a\"\n(or, for gccgo, \"DIR/pkg/gccgo/foo/libbar.a\").\n\nThe bin/ directory holds compiled commands.\nEach command is named for its source directory, but only\nusing the final element, not the entire path. That is, the\ncommand with source in DIR/src/foo/quux is installed into\nDIR/bin/quux, not DIR/bin/foo/quux. The foo/ is stripped\nso that you can add DIR/bin to your PATH to get at the\ninstalled commands.\n\nHere's an example directory layout:\n\n```\nGOPATH=/home/user/gocode\n\n/home/user/gocode/\n src/\n foo/\n bar/ (go code in package bar)\n x.go\n quux/ (go code in package main)\n y.go\n bin/\n quux (installed command)\n pkg/\n linux_amd64/\n foo/\n bar.a (installed package object)\n\n```\nBuild Constraints\n\nA build constraint, also known as a build tag, is a line comment that begins\n\n```\n//go:build\n\n```\nthat lists the conditions under which a file should be included in the\npackage. Build constraints may also be part of a file's name\n(for example, source_windows.go will only be included if the target\noperating system is windows).\n\nSee 'go help buildconstraint'\n(https://golang.org/cmd/go/#hdr-Build_constraints) for details.\n\nBinary-Only Packages\n\nIn Go 1.12 and earlier, it was possible to distribute packages in binary\nform without including the source code used for compiling the package.\nThe package was distributed with a source file not excluded by build\nconstraints and containing a \"//go:binary-only-package\" comment. Like a\nbuild constraint, this comment appeared at the top of a file, preceded\nonly by blank lines and other line comments and with a blank line\nfollowing the comment, to separate it from the package documentation.\nUnlike build constraints, this comment is only recognized in non-test\nGo source files.\n\nThe minimal source code for a binary-only package was therefore:\n\n```\n//go:binary-only-package\n\npackage mypkg\n\n```\nThe source code could include additional Go code. That code was never\ncompiled but would be processed by tools like godoc and might be useful\nas end-user documentation.\n\n\"go build\" and other commands no longer support binary-only-packages.\nImport and ImportDir will still set the BinaryOnly flag in packages\ncontaining these comments for use in tools and error messages.\n\n[\"go/build\" on pkg.go.dev](https://pkg.go.dev/go/build)", + "synopsis": "Package build gathers information about Go packages.\n\n# Go Path\n\nThe Go path is a list of directory trees containing Go source code.\nIt is consulted to resolve imports that cannot be found in the standard\nGo tree. The default path is the value of the GOPATH environment\nvariable, interpreted as a path list appropriate to the operating system\n(on Unix, the variable is a colon-separated string;\non Windows, a semicolon-separated string;\non Plan 9, a list).\n\nEach directory listed in the Go path must have a prescribed structure:\n\nThe src/ directory holds source code. The path below 'src' determines\nthe import path or executable name.\n\nThe pkg/ directory holds installed package objects.\nAs in the Go tree, each target operating system and\narchitecture pair has its own subdirectory of pkg\n(pkg/GOOS_GOARCH).\n\nIf DIR is a directory listed in the Go path, a package with\nsource in DIR/src/foo/bar can be imported as \"foo/bar\" and\nhas its compiled form installed to \"DIR/pkg/GOOS_GOARCH/foo/bar.a\"\n(or, for gccgo, \"DIR/pkg/gccgo/foo/libbar.a\").\n\nThe bin/ directory holds compiled commands.\nEach command is named for its source directory, but only\nusing the final element, not the entire path. That is, the\ncommand with source in DIR/src/foo/quux is installed into\nDIR/bin/quux, not DIR/bin/foo/quux. The foo/ is stripped\nso that you can add DIR/bin to your PATH to get at the\ninstalled commands.\n\nHere's an example directory layout:\n\n```\nGOPATH=/home/user/gocode\n\n/home/user/gocode/\n src/\n foo/\n bar/ (go code in package bar)\n x.go\n quux/ (go code in package main)\n y.go\n bin/\n quux (installed command)\n pkg/\n linux_amd64/\n foo/\n bar.a (installed package object)\n\n```\n# Build Constraints\n\nA build constraint, also known as a build tag, is a condition under which a\nfile should be included in the package. Build constraints are given by a\nline comment that begins\n\n```\n//go:build\n\n```\nBuild constraints may also be part of a file's name\n(for example, source_windows.go will only be included if the target\noperating system is windows).\n\nSee 'go help buildconstraint'\n(https://golang.org/cmd/go/#hdr-Build_constraints) for details.\n\n# Binary-Only Packages\n\nIn Go 1.12 and earlier, it was possible to distribute packages in binary\nform without including the source code used for compiling the package.\nThe package was distributed with a source file not excluded by build\nconstraints and containing a \"//go:binary-only-package\" comment. Like a\nbuild constraint, this comment appeared at the top of a file, preceded\nonly by blank lines and other line comments and with a blank line\nfollowing the comment, to separate it from the package documentation.\nUnlike build constraints, this comment is only recognized in non-test\nGo source files.\n\nThe minimal source code for a binary-only package was therefore:\n\n```\n//go:binary-only-package\n\npackage mypkg\n\n```\nThe source code could include additional Go code. That code was never\ncompiled but would be processed by tools like godoc and might be useful\nas end-user documentation.\n\n\"go build\" and other commands no longer support binary-only-packages.\nImport and ImportDir will still set the BinaryOnly flag in packages\ncontaining these comments for use in tools and error messages.\n\n[\"go/build\" on pkg.go.dev](https://pkg.go.dev/go/build)", "url": "https://pkg.go.dev/go/build", "path": "go/build", "children": [ { "name": "constraint", - "synopsis": "Package constraint implements parsing and evaluation of build constraint lines.\nSee https://golang.org/cmd/go/#hdr-Build_constraints for documentation about build constraints themselves.\n\nThis package parses both the original “// +build” syntax and the “//go:build” syntax that will be added in Go 1.17.\nThe parser is being included in Go 1.16 to allow tools that need to process Go 1.17 source code\nto still be built against the Go 1.16 release.\nSee https://golang.org/design/draft-gobuild for details about the “//go:build” syntax.\n\n[\"go/build/constraint\" on pkg.go.dev](https://pkg.go.dev/go/build/constraint)", + "synopsis": "Package constraint implements parsing and evaluation of build constraint lines.\nSee https://golang.org/cmd/go/#hdr-Build_constraints for documentation about build constraints themselves.\n\nThis package parses both the original “// +build” syntax and the “//go:build” syntax that was added in Go 1.17.\nSee https://golang.org/design/draft-gobuild for details about the “//go:build” syntax.\n\n[\"go/build/constraint\" on pkg.go.dev](https://pkg.go.dev/go/build/constraint)", "url": "https://pkg.go.dev/go/build/constraint", "path": "go/build/constraint", "children": [] @@ -503,7 +561,15 @@ "synopsis": "Package doc extracts source code documentation from a Go AST.\n\n[\"go/doc\" on pkg.go.dev](https://pkg.go.dev/go/doc)", "url": "https://pkg.go.dev/go/doc", "path": "go/doc", - "children": [] + "children": [ + { + "name": "comment", + "synopsis": "Package comment implements parsing and reformatting of Go doc comments,\n(documentation comments), which are comments that immediately precede\na top-level declaration of a package, const, func, type, or var.\n\nGo doc comment syntax is a simplified subset of Markdown that supports\nlinks, headings, paragraphs, lists (without nesting), and preformatted text blocks.\nThe details of the syntax are documented at https://go.dev/doc/comment.\n\nTo parse the text associated with a doc comment (after removing comment markers),\nuse a [Parser]:\n\n```\nvar p comment.Parser\ndoc := p.Parse(text)\n\n```\nThe result is a [*Doc].\nTo reformat it as a doc comment, HTML, Markdown, or plain text,\nuse a [Printer]:\n\n```\nvar pr comment.Printer\nos.Stdout.Write(pr.Text(doc))\n\n```\nThe [Parser] and [Printer] types are structs whose fields can be\nmodified to customize the operations.\nFor details, see the documentation for those types.\n\nUse cases that need additional control over reformatting can\nimplement their own logic by inspecting the parsed syntax itself.\nSee the documentation for [Doc], [Block], [Text] for an overview\nand links to additional types.\n\n[\"go/doc/comment\" on pkg.go.dev](https://pkg.go.dev/go/doc/comment)", + "url": "https://pkg.go.dev/go/doc/comment", + "path": "go/doc/comment", + "children": [] + } + ] }, { "name": "format", @@ -564,7 +630,7 @@ "children": [ { "name": "adler32", - "synopsis": "Package adler32 implements the Adler-32 checksum.\n\nIt is defined in RFC 1950:\n```\nAdler-32 is composed of two sums accumulated per byte: s1 is\nthe sum of all bytes, s2 is the sum of all s1 values. Both sums\nare done modulo 65521. s1 is initialized to 1, s2 to zero. The\nAdler-32 checksum is stored as s2*65536 + s1 in most-\nsignificant-byte first (network) order.\n\n[\"hash/adler32\" on pkg.go.dev](https://pkg.go.dev/hash/adler32)", + "synopsis": "Package adler32 implements the Adler-32 checksum.\n\nIt is defined in RFC 1950:\n\n```\nAdler-32 is composed of two sums accumulated per byte: s1 is\nthe sum of all bytes, s2 is the sum of all s1 values. Both sums\nare done modulo 65521. s1 is initialized to 1, s2 to zero. The\nAdler-32 checksum is stored as s2*65536 + s1 in most-\nsignificant-byte first (network) order.\n\n[\"hash/adler32\" on pkg.go.dev](https://pkg.go.dev/hash/adler32)", "url": "https://pkg.go.dev/hash/adler32", "path": "hash/adler32", "children": [] @@ -607,7 +673,7 @@ "children": [ { "name": "template", - "synopsis": "Package template (html/template) implements data-driven templates for\ngenerating HTML output safe against code injection. It provides the\nsame interface as package text/template and should be used instead of\ntext/template whenever the output is HTML.\n\nThe documentation here focuses on the security features of the package.\nFor information about how to program the templates themselves, see the\ndocumentation for text/template.\n\nIntroduction\n\nThis package wraps package text/template so you can share its template API\nto parse and execute HTML templates safely.\n\n tmpl, err := template.New(\"name\").Parse(...)\n // Error checking elided\n err = tmpl.Execute(out, data)\n\nIf successful, tmpl will now be injection-safe. Otherwise, err is an error\ndefined in the docs for ErrorCode.\n\nHTML templates treat data values as plain text which should be encoded so they\ncan be safely embedded in an HTML document. The escaping is contextual, so\nactions can appear within JavaScript, CSS, and URI contexts.\n\nThe security model used by this package assumes that template authors are\ntrusted, while Execute's data parameter is not. More details are\nprovided below.\n\nExample\n\n import \"text/template\"\n ...\n t, err := template.New(\"foo\").Parse(`{{define \"T\"}}Hello, {{.}}!{{end}}`)\n err = t.ExecuteTemplate(out, \"T\", \"\u003cscript\u003ealert('you have been pwned')\u003c/script\u003e\")\n\nproduces\n\n Hello, \u003cscript\u003ealert('you have been pwned')\u003c/script\u003e!\n\nbut the contextual autoescaping in html/template\n\n import \"html/template\"\n ...\n t, err := template.New(\"foo\").Parse(`{{define \"T\"}}Hello, {{.}}!{{end}}`)\n err = t.ExecuteTemplate(out, \"T\", \"\u003cscript\u003ealert('you have been pwned')\u003c/script\u003e\")\n\nproduces safe, escaped HTML output\n\n Hello, \u0026lt;script\u0026gt;alert(\u0026#39;you have been pwned\u0026#39;)\u0026lt;/script\u0026gt;!\n\nContexts\n\nThis package understands HTML, CSS, JavaScript, and URIs. It adds sanitizing\nfunctions to each simple action pipeline, so given the excerpt\n\n \u003ca href=\"/search?q={{.}}\"\u003e{{.}}\u003c/a\u003e\n\nAt parse time each {{.}} is overwritten to add escaping functions as necessary.\nIn this case it becomes\n\n \u003ca href=\"/search?q={{. | urlescaper | attrescaper}}\"\u003e{{. | htmlescaper}}\u003c/a\u003e\n\nwhere urlescaper, attrescaper, and htmlescaper are aliases for internal escaping\nfunctions.\n\nFor these internal escaping functions, if an action pipeline evaluates to\na nil interface value, it is treated as though it were an empty string.\n\nNamespaced and data- attributes\n\nAttributes with a namespace are treated as if they had no namespace.\nGiven the excerpt\n\n \u003ca my:href=\"{{.}}\"\u003e\u003c/a\u003e\n\nAt parse time the attribute will be treated as if it were just \"href\".\nSo at parse time the template becomes:\n\n \u003ca my:href=\"{{. | urlescaper | attrescaper}}\"\u003e\u003c/a\u003e\n\nSimilarly to attributes with namespaces, attributes with a \"data-\" prefix are\ntreated as if they had no \"data-\" prefix. So given\n\n \u003ca data-href=\"{{.}}\"\u003e\u003c/a\u003e\n\nAt parse time this becomes\n\n \u003ca data-href=\"{{. | urlescaper | attrescaper}}\"\u003e\u003c/a\u003e\n\nIf an attribute has both a namespace and a \"data-\" prefix, only the namespace\nwill be removed when determining the context. For example\n\n \u003ca my:data-href=\"{{.}}\"\u003e\u003c/a\u003e\n\nThis is handled as if \"my:data-href\" was just \"data-href\" and not \"href\" as\nit would be if the \"data-\" prefix were to be ignored too. Thus at parse\ntime this becomes just\n\n \u003ca my:data-href=\"{{. | attrescaper}}\"\u003e\u003c/a\u003e\n\nAs a special case, attributes with the namespace \"xmlns\" are always treated\nas containing URLs. Given the excerpts\n\n \u003ca xmlns:title=\"{{.}}\"\u003e\u003c/a\u003e\n \u003ca xmlns:href=\"{{.}}\"\u003e\u003c/a\u003e\n \u003ca xmlns:onclick=\"{{.}}\"\u003e\u003c/a\u003e\n\nAt parse time they become:\n\n \u003ca xmlns:title=\"{{. | urlescaper | attrescaper}}\"\u003e\u003c/a\u003e\n \u003ca xmlns:href=\"{{. | urlescaper | attrescaper}}\"\u003e\u003c/a\u003e\n \u003ca xmlns:onclick=\"{{. | urlescaper | attrescaper}}\"\u003e\u003c/a\u003e\n\nErrors\n\nSee the documentation of ErrorCode for details.\n\nA fuller picture\n\nThe rest of this package comment may be skipped on first reading; it includes\ndetails necessary to understand escaping contexts and error messages. Most users\nwill not need to understand these details.\n\nContexts\n\nAssuming {{.}} is `O'Reilly: How are \u003ci\u003eyou\u003c/i\u003e?`, the table below shows\nhow {{.}} appears when used in the context to the left.\n\n Context {{.}} After\n {{.}} O'Reilly: How are \u0026lt;i\u0026gt;you\u0026lt;/i\u0026gt;?\n \u003ca title='{{.}}'\u003e O\u0026#39;Reilly: How are you?\n \u003ca href=\"/{{.}}\"\u003e O\u0026#39;Reilly: How are %3ci%3eyou%3c/i%3e?\n \u003ca href=\"?q={{.}}\"\u003e O\u0026#39;Reilly%3a%20How%20are%3ci%3e...%3f\n \u003ca onx='f(\"{{.}}\")'\u003e O\\x27Reilly: How are \\x3ci\\x3eyou...?\n \u003ca onx='f({{.}})'\u003e \"O\\x27Reilly: How are \\x3ci\\x3eyou...?\"\n \u003ca onx='pattern = /{{.}}/;'\u003e O\\x27Reilly: How are \\x3ci\\x3eyou...\\x3f\n\nIf used in an unsafe context, then the value might be filtered out:\n\n Context {{.}} After\n \u003ca href=\"{{.}}\"\u003e #ZgotmplZ\n\nsince \"O'Reilly:\" is not an allowed protocol like \"http:\".\n\nIf {{.}} is the innocuous word, `left`, then it can appear more widely,\n\n Context {{.}} After\n {{.}} left\n \u003ca title='{{.}}'\u003e left\n \u003ca href='{{.}}'\u003e left\n \u003ca href='/{{.}}'\u003e left\n \u003ca href='?dir={{.}}'\u003e left\n \u003ca style=\"border-{{.}}: 4px\"\u003e left\n \u003ca style=\"align: {{.}}\"\u003e left\n \u003ca style=\"background: '{{.}}'\u003e left\n \u003ca style=\"background: url('{{.}}')\u003e left\n \u003cstyle\u003ep.{{.}} {color:red}\u003c/style\u003e left\n\nNon-string values can be used in JavaScript contexts.\nIf {{.}} is\n\n struct{A,B string}{ \"foo\", \"bar\" }\n\nin the escaped template\n\n \u003cscript\u003evar pair = {{.}};\u003c/script\u003e\n\nthen the template output is\n\n \u003cscript\u003evar pair = {\"A\": \"foo\", \"B\": \"bar\"};\u003c/script\u003e\n\nSee package json to understand how non-string content is marshaled for\nembedding in JavaScript contexts.\n\nTyped Strings\n\nBy default, this package assumes that all pipelines produce a plain text string.\nIt adds escaping pipeline stages necessary to correctly and safely embed that\nplain text string in the appropriate context.\n\nWhen a data value is not plain text, you can make sure it is not over-escaped\nby marking it with its type.\n\nTypes HTML, JS, URL, and others from content.go can carry safe content that is\nexempted from escaping.\n\nThe template\n\n Hello, {{.}}!\n\ncan be invoked with\n\n tmpl.Execute(out, template.HTML(`\u003cb\u003eWorld\u003c/b\u003e`))\n\nto produce\n\n Hello, \u003cb\u003eWorld\u003c/b\u003e!\n\ninstead of the\n\n Hello, \u0026lt;b\u0026gt;World\u0026lt;b\u0026gt;!\n\nthat would have been produced if {{.}} was a regular string.\n\nSecurity Model\n\nhttps://rawgit.com/mikesamuel/sanitized-jquery-templates/trunk/safetemplate.html#problem_definition defines \"safe\" as used by this package.\n\nThis package assumes that template authors are trusted, that Execute's data\nparameter is not, and seeks to preserve the properties below in the face\nof untrusted data:\n\nStructure Preservation Property:\n\"... when a template author writes an HTML tag in a safe templating language,\nthe browser will interpret the corresponding portion of the output as a tag\nregardless of the values of untrusted data, and similarly for other structures\nsuch as attribute boundaries and JS and CSS string boundaries.\"\n\nCode Effect Property:\n\"... only code specified by the template author should run as a result of\ninjecting the template output into a page and all code specified by the\ntemplate author should run as a result of the same.\"\n\nLeast Surprise Property:\n\"A developer (or code reviewer) familiar with HTML, CSS, and JavaScript, who\nknows that contextual autoescaping happens should be able to look at a {{.}}\nand correctly infer what sanitization happens.\"\n\n[\"html/template\" on pkg.go.dev](https://pkg.go.dev/html/template)", + "synopsis": "Package template (html/template) implements data-driven templates for\ngenerating HTML output safe against code injection. It provides the\nsame interface as [text/template] and should be used instead of\n[text/template] whenever the output is HTML.\n\nThe documentation here focuses on the security features of the package.\nFor information about how to program the templates themselves, see the\ndocumentation for [text/template].\n\n# Introduction\n\nThis package wraps [text/template] so you can share its template API\nto parse and execute HTML templates safely.\n\n```\ntmpl, err := template.New(\"name\").Parse(...)\n// Error checking elided\nerr = tmpl.Execute(out, data)\n\n```\nIf successful, tmpl will now be injection-safe. Otherwise, err is an error\ndefined in the docs for ErrorCode.\n\nHTML templates treat data values as plain text which should be encoded so they\ncan be safely embedded in an HTML document. The escaping is contextual, so\nactions can appear within JavaScript, CSS, and URI contexts.\n\nThe security model used by this package assumes that template authors are\ntrusted, while Execute's data parameter is not. More details are\nprovided below.\n\nExample\n\n```\nimport \"text/template\"\n...\nt, err := template.New(\"foo\").Parse(`{{define \"T\"}}Hello, {{.}}!{{end}}`)\nerr = t.ExecuteTemplate(out, \"T\", \"\u003cscript\u003ealert('you have been pwned')\u003c/script\u003e\")\n\n```\nproduces\n\n```\nHello, \u003cscript\u003ealert('you have been pwned')\u003c/script\u003e!\n\n```\nbut the contextual autoescaping in html/template\n\n```\nimport \"html/template\"\n...\nt, err := template.New(\"foo\").Parse(`{{define \"T\"}}Hello, {{.}}!{{end}}`)\nerr = t.ExecuteTemplate(out, \"T\", \"\u003cscript\u003ealert('you have been pwned')\u003c/script\u003e\")\n\n```\nproduces safe, escaped HTML output\n\n```\nHello, \u0026lt;script\u0026gt;alert(\u0026#39;you have been pwned\u0026#39;)\u0026lt;/script\u0026gt;!\n\n```\n# Contexts\n\nThis package understands HTML, CSS, JavaScript, and URIs. It adds sanitizing\nfunctions to each simple action pipeline, so given the excerpt\n\n```\n\u003ca href=\"/search?q={{.}}\"\u003e{{.}}\u003c/a\u003e\n\n```\nAt parse time each {{.}} is overwritten to add escaping functions as necessary.\nIn this case it becomes\n\n```\n\u003ca href=\"/search?q={{. | urlescaper | attrescaper}}\"\u003e{{. | htmlescaper}}\u003c/a\u003e\n\n```\nwhere urlescaper, attrescaper, and htmlescaper are aliases for internal escaping\nfunctions.\n\nFor these internal escaping functions, if an action pipeline evaluates to\na nil interface value, it is treated as though it were an empty string.\n\n# Namespaced and data- attributes\n\nAttributes with a namespace are treated as if they had no namespace.\nGiven the excerpt\n\n```\n\u003ca my:href=\"{{.}}\"\u003e\u003c/a\u003e\n\n```\nAt parse time the attribute will be treated as if it were just \"href\".\nSo at parse time the template becomes:\n\n```\n\u003ca my:href=\"{{. | urlescaper | attrescaper}}\"\u003e\u003c/a\u003e\n\n```\nSimilarly to attributes with namespaces, attributes with a \"data-\" prefix are\ntreated as if they had no \"data-\" prefix. So given\n\n```\n\u003ca data-href=\"{{.}}\"\u003e\u003c/a\u003e\n\n```\nAt parse time this becomes\n\n```\n\u003ca data-href=\"{{. | urlescaper | attrescaper}}\"\u003e\u003c/a\u003e\n\n```\nIf an attribute has both a namespace and a \"data-\" prefix, only the namespace\nwill be removed when determining the context. For example\n\n```\n\u003ca my:data-href=\"{{.}}\"\u003e\u003c/a\u003e\n\n```\nThis is handled as if \"my:data-href\" was just \"data-href\" and not \"href\" as\nit would be if the \"data-\" prefix were to be ignored too. Thus at parse\ntime this becomes just\n\n```\n\u003ca my:data-href=\"{{. | attrescaper}}\"\u003e\u003c/a\u003e\n\n```\nAs a special case, attributes with the namespace \"xmlns\" are always treated\nas containing URLs. Given the excerpts\n\n```\n\u003ca xmlns:title=\"{{.}}\"\u003e\u003c/a\u003e\n\u003ca xmlns:href=\"{{.}}\"\u003e\u003c/a\u003e\n\u003ca xmlns:onclick=\"{{.}}\"\u003e\u003c/a\u003e\n\n```\nAt parse time they become:\n\n```\n\u003ca xmlns:title=\"{{. | urlescaper | attrescaper}}\"\u003e\u003c/a\u003e\n\u003ca xmlns:href=\"{{. | urlescaper | attrescaper}}\"\u003e\u003c/a\u003e\n\u003ca xmlns:onclick=\"{{. | urlescaper | attrescaper}}\"\u003e\u003c/a\u003e\n\n```\n# Errors\n\nSee the documentation of ErrorCode for details.\n\n# A fuller picture\n\nThe rest of this package comment may be skipped on first reading; it includes\ndetails necessary to understand escaping contexts and error messages. Most users\nwill not need to understand these details.\n\n# Contexts\n\nAssuming {{.}} is `O'Reilly: How are \u003ci\u003eyou\u003c/i\u003e?`, the table below shows\nhow {{.}} appears when used in the context to the left.\n\n```\nContext {{.}} After\n{{.}} O'Reilly: How are \u0026lt;i\u0026gt;you\u0026lt;/i\u0026gt;?\n\u003ca title='{{.}}'\u003e O\u0026#39;Reilly: How are you?\n\u003ca href=\"/{{.}}\"\u003e O\u0026#39;Reilly: How are %3ci%3eyou%3c/i%3e?\n\u003ca href=\"?q={{.}}\"\u003e O\u0026#39;Reilly%3a%20How%20are%3ci%3e...%3f\n\u003ca onx='f(\"{{.}}\")'\u003e O\\x27Reilly: How are \\x3ci\\x3eyou...?\n\u003ca onx='f({{.}})'\u003e \"O\\x27Reilly: How are \\x3ci\\x3eyou...?\"\n\u003ca onx='pattern = /{{.}}/;'\u003e O\\x27Reilly: How are \\x3ci\\x3eyou...\\x3f\n\n```\nIf used in an unsafe context, then the value might be filtered out:\n\n```\nContext {{.}} After\n\u003ca href=\"{{.}}\"\u003e #ZgotmplZ\n\n```\nsince \"O'Reilly:\" is not an allowed protocol like \"http:\".\n\nIf {{.}} is the innocuous word, `left`, then it can appear more widely,\n\n```\nContext {{.}} After\n{{.}} left\n\u003ca title='{{.}}'\u003e left\n\u003ca href='{{.}}'\u003e left\n\u003ca href='/{{.}}'\u003e left\n\u003ca href='?dir={{.}}'\u003e left\n\u003ca style=\"border-{{.}}: 4px\"\u003e left\n\u003ca style=\"align: {{.}}\"\u003e left\n\u003ca style=\"background: '{{.}}'\u003e left\n\u003ca style=\"background: url('{{.}}')\u003e left\n\u003cstyle\u003ep.{{.}} {color:red}\u003c/style\u003e left\n\n```\nNon-string values can be used in JavaScript contexts.\nIf {{.}} is\n\n```\nstruct{A,B string}{ \"foo\", \"bar\" }\n\n```\nin the escaped template\n\n```\n\u003cscript\u003evar pair = {{.}};\u003c/script\u003e\n\n```\nthen the template output is\n\n```\n\u003cscript\u003evar pair = {\"A\": \"foo\", \"B\": \"bar\"};\u003c/script\u003e\n\n```\nSee package json to understand how non-string content is marshaled for\nembedding in JavaScript contexts.\n\n# Typed Strings\n\nBy default, this package assumes that all pipelines produce a plain text string.\nIt adds escaping pipeline stages necessary to correctly and safely embed that\nplain text string in the appropriate context.\n\nWhen a data value is not plain text, you can make sure it is not over-escaped\nby marking it with its type.\n\nTypes HTML, JS, URL, and others from content.go can carry safe content that is\nexempted from escaping.\n\nThe template\n\n```\nHello, {{.}}!\n\n```\ncan be invoked with\n\n```\ntmpl.Execute(out, template.HTML(`\u003cb\u003eWorld\u003c/b\u003e`))\n\n```\nto produce\n\n```\nHello, \u003cb\u003eWorld\u003c/b\u003e!\n\n```\ninstead of the\n\n```\nHello, \u0026lt;b\u0026gt;World\u0026lt;b\u0026gt;!\n\n```\nthat would have been produced if {{.}} was a regular string.\n\n# Security Model\n\nhttps://rawgit.com/mikesamuel/sanitized-jquery-templates/trunk/safetemplate.html#problem_definition defines \"safe\" as used by this package.\n\nThis package assumes that template authors are trusted, that Execute's data\nparameter is not, and seeks to preserve the properties below in the face\nof untrusted data:\n\nStructure Preservation Property:\n\"... when a template author writes an HTML tag in a safe templating language,\nthe browser will interpret the corresponding portion of the output as a tag\nregardless of the values of untrusted data, and similarly for other structures\nsuch as attribute boundaries and JS and CSS string boundaries.\"\n\nCode Effect Property:\n\"... only code specified by the template author should run as a result of\ninjecting the template output into a page and all code specified by the\ntemplate author should run as a result of the same.\"\n\nLeast Surprise Property:\n\"A developer (or code reviewer) familiar with HTML, CSS, and JavaScript, who\nknows that contextual autoescaping happens should be able to look at a {{.}}\nand correctly infer what sanitization happens.\"\n\nAs a consequence of the Least Surprise Property, template actions within an\nECMAScript 6 template literal are disabled by default.\nHandling string interpolation within these literals is rather complex resulting\nin no clear safe way to support it.\nTo re-enable template actions within ECMAScript 6 template literals, use the\nGODEBUG=jstmpllitinterp=1 environment variable.\n\n[\"html/template\" on pkg.go.dev](https://pkg.go.dev/html/template)", "url": "https://pkg.go.dev/html/template", "path": "html/template", "children": [] @@ -616,7 +682,7 @@ }, { "name": "image", - "synopsis": "Package image implements a basic 2-D image library.\n\nThe fundamental interface is called Image. An Image contains colors, which\nare described in the image/color package.\n\nValues of the Image interface are created either by calling functions such\nas NewRGBA and NewPaletted, or by calling Decode on an io.Reader containing\nimage data in a format such as GIF, JPEG or PNG. Decoding any particular\nimage format requires the prior registration of a decoder function.\nRegistration is typically automatic as a side effect of initializing that\nformat's package so that, to decode a PNG image, it suffices to have\n```\nimport _ \"image/png\"\n```\nin a program's main package. The _ means to import a package purely for its\ninitialization side effects.\n\nSee \"The Go image package\" for more details:\nhttps://golang.org/doc/articles/image_package.html\n\n[\"image\" on pkg.go.dev](https://pkg.go.dev/image)", + "synopsis": "Package image implements a basic 2-D image library.\n\nThe fundamental interface is called Image. An Image contains colors, which\nare described in the image/color package.\n\nValues of the Image interface are created either by calling functions such\nas NewRGBA and NewPaletted, or by calling Decode on an io.Reader containing\nimage data in a format such as GIF, JPEG or PNG. Decoding any particular\nimage format requires the prior registration of a decoder function.\nRegistration is typically automatic as a side effect of initializing that\nformat's package so that, to decode a PNG image, it suffices to have\n\n```\nimport _ \"image/png\"\n\n```\nin a program's main package. The _ means to import a package purely for its\ninitialization side effects.\n\nSee \"The Go image package\" for more details:\nhttps://golang.org/doc/articles/image_package.html\n\n[\"image\" on pkg.go.dev](https://pkg.go.dev/image)", "url": "https://pkg.go.dev/image", "path": "image", "children": [ @@ -695,7 +761,7 @@ }, { "name": "ioutil", - "synopsis": "Package ioutil implements some I/O utility functions.\n\nAs of Go 1.16, the same functionality is now provided\nby package io or package os, and those implementations\nshould be preferred in new code.\nSee the specific function documentation for details.\n\n[\"io/ioutil\" on pkg.go.dev](https://pkg.go.dev/io/ioutil)", + "synopsis": "Package ioutil implements some I/O utility functions.\n\nDeprecated: As of Go 1.16, the same functionality is now provided\nby package [io] or package [os], and those implementations\nshould be preferred in new code.\nSee the specific function documentation for details.\n\n[\"io/ioutil\" on pkg.go.dev](https://pkg.go.dev/io/ioutil)", "url": "https://pkg.go.dev/io/ioutil", "path": "io/ioutil", "children": [] @@ -708,15 +774,29 @@ "url": "https://pkg.go.dev/log", "path": "log", "children": [ + { + "name": "slog", + "synopsis": "Package slog provides structured logging,\nin which log records include a message,\na severity level, and various other attributes\nexpressed as key-value pairs.\n\nIt defines a type, [Logger],\nwhich provides several methods (such as [Logger.Info] and [Logger.Error])\nfor reporting events of interest.\n\nEach Logger is associated with a [Handler].\nA Logger output method creates a [Record] from the method arguments\nand passes it to the Handler, which decides how to handle it.\nThere is a default Logger accessible through top-level functions\n(such as [Info] and [Error]) that call the corresponding Logger methods.\n\nA log record consists of a time, a level, a message, and a set of key-value\npairs, where the keys are strings and the values may be of any type.\nAs an example,\n\n```\nslog.Info(\"hello\", \"count\", 3)\n\n```\ncreates a record containing the time of the call,\na level of Info, the message \"hello\", and a single\npair with key \"count\" and value 3.\n\nThe [Info] top-level function calls the [Logger.Info] method on the default Logger.\nIn addition to [Logger.Info], there are methods for Debug, Warn and Error levels.\nBesides these convenience methods for common levels,\nthere is also a [Logger.Log] method which takes the level as an argument.\nEach of these methods has a corresponding top-level function that uses the\ndefault logger.\n\nThe default handler formats the log record's message, time, level, and attributes\nas a string and passes it to the [log] package.\n\n```\n2022/11/08 15:28:26 INFO hello count=3\n\n```\nFor more control over the output format, create a logger with a different handler.\nThis statement uses [New] to create a new logger with a TextHandler\nthat writes structured records in text form to standard error:\n\n```\nlogger := slog.New(slog.NewTextHandler(os.Stderr, nil))\n\n```\n[TextHandler] output is a sequence of key=value pairs, easily and unambiguously\nparsed by machine. This statement:\n\n```\nlogger.Info(\"hello\", \"count\", 3)\n\n```\nproduces this output:\n\n```\ntime=2022-11-08T15:28:26.000-05:00 level=INFO msg=hello count=3\n\n```\nThe package also provides [JSONHandler], whose output is line-delimited JSON:\n\n```\nlogger := slog.New(slog.NewJSONHandler(os.Stdout, nil))\nlogger.Info(\"hello\", \"count\", 3)\n\n```\nproduces this output:\n\n```\n{\"time\":\"2022-11-08T15:28:26.000000000-05:00\",\"level\":\"INFO\",\"msg\":\"hello\",\"count\":3}\n\n```\nBoth [TextHandler] and [JSONHandler] can be configured with [HandlerOptions].\nThere are options for setting the minimum level (see Levels, below),\ndisplaying the source file and line of the log call, and\nmodifying attributes before they are logged.\n\nSetting a logger as the default with\n\n```\nslog.SetDefault(logger)\n\n```\nwill cause the top-level functions like [Info] to use it.\n[SetDefault] also updates the default logger used by the [log] package,\nso that existing applications that use [log.Printf] and related functions\nwill send log records to the logger's handler without needing to be rewritten.\n\nSome attributes are common to many log calls.\nFor example, you may wish to include the URL or trace identifier of a server request\nwith all log events arising from the request.\nRather than repeat the attribute with every log call, you can use [Logger.With]\nto construct a new Logger containing the attributes:\n\n```\nlogger2 := logger.With(\"url\", r.URL)\n\n```\nThe arguments to With are the same key-value pairs used in [Logger.Info].\nThe result is a new Logger with the same handler as the original, but additional\nattributes that will appear in the output of every call.\n\n# Levels\n\nA [Level] is an integer representing the importance or severity of a log event.\nThe higher the level, the more severe the event.\nThis package defines constants for the most common levels,\nbut any int can be used as a level.\n\nIn an application, you may wish to log messages only at a certain level or greater.\nOne common configuration is to log messages at Info or higher levels,\nsuppressing debug logging until it is needed.\nThe built-in handlers can be configured with the minimum level to output by\nsetting [HandlerOptions.Level].\nThe program's `main` function typically does this.\nThe default value is LevelInfo.\n\nSetting the [HandlerOptions.Level] field to a [Level] value\nfixes the handler's minimum level throughout its lifetime.\nSetting it to a [LevelVar] allows the level to be varied dynamically.\nA LevelVar holds a Level and is safe to read or write from multiple\ngoroutines.\nTo vary the level dynamically for an entire program, first initialize\na global LevelVar:\n\n```\nvar programLevel = new(slog.LevelVar) // Info by default\n\n```\nThen use the LevelVar to construct a handler, and make it the default:\n\n```\nh := slog.NewJSONHandler(os.Stderr, \u0026slog.HandlerOptions{Level: programLevel})\nslog.SetDefault(slog.New(h))\n\n```\nNow the program can change its logging level with a single statement:\n\n```\nprogramLevel.Set(slog.LevelDebug)\n\n```\n# Groups\n\nAttributes can be collected into groups.\nA group has a name that is used to qualify the names of its attributes.\nHow this qualification is displayed depends on the handler.\n[TextHandler] separates the group and attribute names with a dot.\n[JSONHandler] treats each group as a separate JSON object, with the group name as the key.\n\nUse [Group] to create a Group attribute from a name and a list of key-value pairs:\n\n```\nslog.Group(\"request\",\n \"method\", r.Method,\n \"url\", r.URL)\n\n```\nTextHandler would display this group as\n\n```\nrequest.method=GET request.url=http://example.com\n\n```\nJSONHandler would display it as\n\n```\n\"request\":{\"method\":\"GET\",\"url\":\"http://example.com\"}\n\n```\nUse [Logger.WithGroup] to qualify all of a Logger's output\nwith a group name. Calling WithGroup on a Logger results in a\nnew Logger with the same Handler as the original, but with all\nits attributes qualified by the group name.\n\nThis can help prevent duplicate attribute keys in large systems,\nwhere subsystems might use the same keys.\nPass each subsystem a different Logger with its own group name so that\npotential duplicates are qualified:\n\n```\nlogger := slog.Default().With(\"id\", systemID)\nparserLogger := logger.WithGroup(\"parser\")\nparseInput(input, parserLogger)\n\n```\nWhen parseInput logs with parserLogger, its keys will be qualified with \"parser\",\nso even if it uses the common key \"id\", the log line will have distinct keys.\n\n# Contexts\n\nSome handlers may wish to include information from the [context.Context] that is\navailable at the call site. One example of such information\nis the identifier for the current span when tracing is enabled.\n\nThe [Logger.Log] and [Logger.LogAttrs] methods take a context as a first\nargument, as do their corresponding top-level functions.\n\nAlthough the convenience methods on Logger (Info and so on) and the\ncorresponding top-level functions do not take a context, the alternatives ending\nin \"Context\" do. For example,\n\n```\nslog.InfoContext(ctx, \"message\")\n\n```\nIt is recommended to pass a context to an output method if one is available.\n\n# Attrs and Values\n\nAn [Attr] is a key-value pair. The Logger output methods accept Attrs as well as\nalternating keys and values. The statement\n\n```\nslog.Info(\"hello\", slog.Int(\"count\", 3))\n\n```\nbehaves the same as\n\n```\nslog.Info(\"hello\", \"count\", 3)\n\n```\nThere are convenience constructors for [Attr] such as [Int], [String], and [Bool]\nfor common types, as well as the function [Any] for constructing Attrs of any\ntype.\n\nThe value part of an Attr is a type called [Value].\nLike an [any], a Value can hold any Go value,\nbut it can represent typical values, including all numbers and strings,\nwithout an allocation.\n\nFor the most efficient log output, use [Logger.LogAttrs].\nIt is similar to [Logger.Log] but accepts only Attrs, not alternating\nkeys and values; this allows it, too, to avoid allocation.\n\nThe call\n\n```\nlogger.LogAttrs(ctx, slog.LevelInfo, \"hello\", slog.Int(\"count\", 3))\n\n```\nis the most efficient way to achieve the same output as\n\n```\nslog.Info(\"hello\", \"count\", 3)\n\n```\n# Customizing a type's logging behavior\n\nIf a type implements the [LogValuer] interface, the [Value] returned from its LogValue\nmethod is used for logging. You can use this to control how values of the type\nappear in logs. For example, you can redact secret information like passwords,\nor gather a struct's fields in a Group. See the examples under [LogValuer] for\ndetails.\n\nA LogValue method may return a Value that itself implements [LogValuer]. The [Value.Resolve]\nmethod handles these cases carefully, avoiding infinite loops and unbounded recursion.\nHandler authors and others may wish to use Value.Resolve instead of calling LogValue directly.\n\n# Wrapping output methods\n\nThe logger functions use reflection over the call stack to find the file name\nand line number of the logging call within the application. This can produce\nincorrect source information for functions that wrap slog. For instance, if you\ndefine this function in file mylog.go:\n\n```\nfunc Infof(format string, args ...any) {\n slog.Default().Info(fmt.Sprintf(format, args...))\n}\n\n```\nand you call it like this in main.go:\n\n```\nInfof(slog.Default(), \"hello, %s\", \"world\")\n\n```\nthen slog will report the source file as mylog.go, not main.go.\n\nA correct implementation of Infof will obtain the source location\n(pc) and pass it to NewRecord.\nThe Infof function in the package-level example called \"wrapping\"\ndemonstrates how to do this.\n\n# Working with Records\n\nSometimes a Handler will need to modify a Record\nbefore passing it on to another Handler or backend.\nA Record contains a mixture of simple public fields (e.g. Time, Level, Message)\nand hidden fields that refer to state (such as attributes) indirectly. This\nmeans that modifying a simple copy of a Record (e.g. by calling\n[Record.Add] or [Record.AddAttrs] to add attributes)\nmay have unexpected effects on the original.\nBefore modifying a Record, use [Record.Clone] to\ncreate a copy that shares no state with the original,\nor create a new Record with [NewRecord]\nand build up its Attrs by traversing the old ones with [Record.Attrs].\n\n# Performance considerations\n\nIf profiling your application demonstrates that logging is taking significant time,\nthe following suggestions may help.\n\nIf many log lines have a common attribute, use [Logger.With] to create a Logger with\nthat attribute. The built-in handlers will format that attribute only once, at the\ncall to [Logger.With]. The [Handler] interface is designed to allow that optimization,\nand a well-written Handler should take advantage of it.\n\nThe arguments to a log call are always evaluated, even if the log event is discarded.\nIf possible, defer computation so that it happens only if the value is actually logged.\nFor example, consider the call\n\n```\nslog.Info(\"starting request\", \"url\", r.URL.String()) // may compute String unnecessarily\n\n```\nThe URL.String method will be called even if the logger discards Info-level events.\nInstead, pass the URL directly:\n\n```\nslog.Info(\"starting request\", \"url\", \u0026r.URL) // calls URL.String only if needed\n\n```\nThe built-in [TextHandler] will call its String method, but only\nif the log event is enabled.\nAvoiding the call to String also preserves the structure of the underlying value.\nFor example [JSONHandler] emits the components of the parsed URL as a JSON object.\nIf you want to avoid eagerly paying the cost of the String call\nwithout causing the handler to potentially inspect the structure of the value,\nwrap the value in a fmt.Stringer implementation that hides its Marshal methods.\n\nYou can also use the [LogValuer] interface to avoid unnecessary work in disabled log\ncalls. Say you need to log some expensive value:\n\n```\nslog.Debug(\"frobbing\", \"value\", computeExpensiveValue(arg))\n\n```\nEven if this line is disabled, computeExpensiveValue will be called.\nTo avoid that, define a type implementing LogValuer:\n\n```\ntype expensive struct { arg int }\n\nfunc (e expensive) LogValue() slog.Value {\n return slog.AnyValue(computeExpensiveValue(e.arg))\n}\n\n```\nThen use a value of that type in log calls:\n\n```\nslog.Debug(\"frobbing\", \"value\", expensive{arg})\n\n```\nNow computeExpensiveValue will only be called when the line is enabled.\n\nThe built-in handlers acquire a lock before calling [io.Writer.Write]\nto ensure that each record is written in one piece. User-defined\nhandlers are responsible for their own locking.\n\n# Writing a handler\n\nFor a guide to writing a custom handler, see https://golang.org/s/slog-handler-guide.\n\n[\"log/slog\" on pkg.go.dev](https://pkg.go.dev/log/slog)", + "url": "https://pkg.go.dev/log/slog", + "path": "log/slog", + "children": [] + }, { "name": "syslog", - "synopsis": "Package syslog provides a simple interface to the system log\nservice. It can send messages to the syslog daemon using UNIX\ndomain sockets, UDP or TCP.\n\nOnly one call to Dial is necessary. On write failures,\nthe syslog client will attempt to reconnect to the server\nand write again.\n\nThe syslog package is frozen and is not accepting new features.\nSome external packages provide more functionality. See:\n\n https://godoc.org/?q=syslog\n\n[\"log/syslog\" on pkg.go.dev](https://pkg.go.dev/log/syslog)", + "synopsis": "Package syslog provides a simple interface to the system log\nservice. It can send messages to the syslog daemon using UNIX\ndomain sockets, UDP or TCP.\n\nOnly one call to Dial is necessary. On write failures,\nthe syslog client will attempt to reconnect to the server\nand write again.\n\nThe syslog package is frozen and is not accepting new features.\nSome external packages provide more functionality. See:\n\n```\nhttps://godoc.org/?q=syslog\n\n[\"log/syslog\" on pkg.go.dev](https://pkg.go.dev/log/syslog)", "url": "https://pkg.go.dev/log/syslog", "path": "log/syslog", "children": [] } ] }, + { + "name": "maps", + "synopsis": "Package maps defines various functions useful with maps of any type.\n\n[\"maps\" on pkg.go.dev](https://pkg.go.dev/maps)", + "url": "https://pkg.go.dev/maps", + "path": "maps", + "children": [] + }, { "name": "math", "synopsis": "Package math provides basic constants and mathematical functions.\n\nThis package does not guarantee bit-identical results across architectures.\n\n[\"math\" on pkg.go.dev](https://pkg.go.dev/math)", @@ -725,14 +805,14 @@ "children": [ { "name": "big", - "synopsis": "Package big implements arbitrary-precision arithmetic (big numbers).\nThe following numeric types are supported:\n\n```\nInt signed integers\nRat rational numbers\nFloat floating-point numbers\n\n```\nThe zero value for an Int, Rat, or Float correspond to 0. Thus, new\nvalues can be declared in the usual ways and denote 0 without further\ninitialization:\n\n```\nvar x Int // \u0026x is an *Int of value 0\nvar r = \u0026Rat{} // r is a *Rat of value 0\ny := new(Float) // y is a *Float of value 0\n\n```\nAlternatively, new values can be allocated and initialized with factory\nfunctions of the form:\n\n```\nfunc NewT(v V) *T\n\n```\nFor instance, NewInt(x) returns an *Int set to the value of the int64\nargument x, NewRat(a, b) returns a *Rat set to the fraction a/b where\na and b are int64 values, and NewFloat(f) returns a *Float initialized\nto the float64 argument f. More flexibility is provided with explicit\nsetters, for instance:\n\n```\nvar z1 Int\nz1.SetUint64(123) // z1 := 123\nz2 := new(Rat).SetFloat64(1.25) // z2 := 5/4\nz3 := new(Float).SetInt(z1) // z3 := 123.0\n\n```\nSetters, numeric operations and predicates are represented as methods of\nthe form:\n\n```\nfunc (z *T) SetV(v V) *T // z = v\nfunc (z *T) Unary(x *T) *T // z = unary x\nfunc (z *T) Binary(x, y *T) *T // z = x binary y\nfunc (x *T) Pred() P // p = pred(x)\n\n```\nwith T one of Int, Rat, or Float. For unary and binary operations, the\nresult is the receiver (usually named z in that case; see below); if it\nis one of the operands x or y it may be safely overwritten (and its memory\nreused).\n\nArithmetic expressions are typically written as a sequence of individual\nmethod calls, with each call corresponding to an operation. The receiver\ndenotes the result and the method arguments are the operation's operands.\nFor instance, given three *Int values a, b and c, the invocation\n\n```\nc.Add(a, b)\n\n```\ncomputes the sum a + b and stores the result in c, overwriting whatever\nvalue was held in c before. Unless specified otherwise, operations permit\naliasing of parameters, so it is perfectly ok to write\n\n```\nsum.Add(sum, x)\n\n```\nto accumulate values x in a sum.\n\n(By always passing in a result value via the receiver, memory use can be\nmuch better controlled. Instead of having to allocate new memory for each\nresult, an operation can reuse the space allocated for the result value,\nand overwrite that value with the new result in the process.)\n\nNotational convention: Incoming method parameters (including the receiver)\nare named consistently in the API to clarify their use. Incoming operands\nare usually named x, y, a, b, and so on, but never z. A parameter specifying\nthe result is named z (typically the receiver).\n\nFor instance, the arguments for (*Int).Add are named x and y, and because\nthe receiver specifies the result destination, it is called z:\n\n```\nfunc (z *Int) Add(x, y *Int) *Int\n\n```\nMethods of this form typically return the incoming receiver as well, to\nenable simple call chaining.\n\nMethods which don't require a result value to be passed in (for instance,\nInt.Sign), simply return the result. In this case, the receiver is typically\nthe first operand, named x:\n\n```\nfunc (x *Int) Sign() int\n\n```\nVarious methods support conversions between strings and corresponding\nnumeric values, and vice versa: *Int, *Rat, and *Float values implement\nthe Stringer interface for a (default) string representation of the value,\nbut also provide SetString methods to initialize a value from a string in\na variety of supported formats (see the respective SetString documentation).\n\nFinally, *Int, *Rat, and *Float satisfy the fmt package's Scanner interface\nfor scanning and (except for *Rat) the Formatter interface for formatted\nprinting.\n\n[\"math/big\" on pkg.go.dev](https://pkg.go.dev/math/big)", + "synopsis": "Package big implements arbitrary-precision arithmetic (big numbers).\nThe following numeric types are supported:\n\n```\nInt signed integers\nRat rational numbers\nFloat floating-point numbers\n\n```\nThe zero value for an Int, Rat, or Float correspond to 0. Thus, new\nvalues can be declared in the usual ways and denote 0 without further\ninitialization:\n\n```\nvar x Int // \u0026x is an *Int of value 0\nvar r = \u0026Rat{} // r is a *Rat of value 0\ny := new(Float) // y is a *Float of value 0\n\n```\nAlternatively, new values can be allocated and initialized with factory\nfunctions of the form:\n\n```\nfunc NewT(v V) *T\n\n```\nFor instance, NewInt(x) returns an *Int set to the value of the int64\nargument x, NewRat(a, b) returns a *Rat set to the fraction a/b where\na and b are int64 values, and NewFloat(f) returns a *Float initialized\nto the float64 argument f. More flexibility is provided with explicit\nsetters, for instance:\n\n```\nvar z1 Int\nz1.SetUint64(123) // z1 := 123\nz2 := new(Rat).SetFloat64(1.25) // z2 := 5/4\nz3 := new(Float).SetInt(z1) // z3 := 123.0\n\n```\nSetters, numeric operations and predicates are represented as methods of\nthe form:\n\n```\nfunc (z *T) SetV(v V) *T // z = v\nfunc (z *T) Unary(x *T) *T // z = unary x\nfunc (z *T) Binary(x, y *T) *T // z = x binary y\nfunc (x *T) Pred() P // p = pred(x)\n\n```\nwith T one of Int, Rat, or Float. For unary and binary operations, the\nresult is the receiver (usually named z in that case; see below); if it\nis one of the operands x or y it may be safely overwritten (and its memory\nreused).\n\nArithmetic expressions are typically written as a sequence of individual\nmethod calls, with each call corresponding to an operation. The receiver\ndenotes the result and the method arguments are the operation's operands.\nFor instance, given three *Int values a, b and c, the invocation\n\n```\nc.Add(a, b)\n\n```\ncomputes the sum a + b and stores the result in c, overwriting whatever\nvalue was held in c before. Unless specified otherwise, operations permit\naliasing of parameters, so it is perfectly ok to write\n\n```\nsum.Add(sum, x)\n\n```\nto accumulate values x in a sum.\n\n(By always passing in a result value via the receiver, memory use can be\nmuch better controlled. Instead of having to allocate new memory for each\nresult, an operation can reuse the space allocated for the result value,\nand overwrite that value with the new result in the process.)\n\nNotational convention: Incoming method parameters (including the receiver)\nare named consistently in the API to clarify their use. Incoming operands\nare usually named x, y, a, b, and so on, but never z. A parameter specifying\nthe result is named z (typically the receiver).\n\nFor instance, the arguments for (*Int).Add are named x and y, and because\nthe receiver specifies the result destination, it is called z:\n\n```\nfunc (z *Int) Add(x, y *Int) *Int\n\n```\nMethods of this form typically return the incoming receiver as well, to\nenable simple call chaining.\n\nMethods which don't require a result value to be passed in (for instance,\nInt.Sign), simply return the result. In this case, the receiver is typically\nthe first operand, named x:\n\n```\nfunc (x *Int) Sign() int\n\n```\nVarious methods support conversions between strings and corresponding\nnumeric values, and vice versa: *Int, *Rat, and *Float values implement\nthe Stringer interface for a (default) string representation of the value,\nbut also provide SetString methods to initialize a value from a string in\na variety of supported formats (see the respective SetString documentation).\n\nFinally, *Int, *Rat, and *Float satisfy [fmt.Scanner] for scanning\nand (except for *Rat) the Formatter interface for formatted printing.\n\n[\"math/big\" on pkg.go.dev](https://pkg.go.dev/math/big)", "url": "https://pkg.go.dev/math/big", "path": "math/big", "children": [] }, { "name": "bits", - "synopsis": "Package bits implements bit counting and manipulation\nfunctions for the predeclared unsigned integer types.\n\n[\"math/bits\" on pkg.go.dev](https://pkg.go.dev/math/bits)", + "synopsis": "Package bits implements bit counting and manipulation\nfunctions for the predeclared unsigned integer types.\n\nFunctions in this package may be implemented directly by\nthe compiler, for better performance. For those functions\nthe code in this package will not be used. Which\nfunctions are implemented by the compiler depends on the\narchitecture and the Go release.\n\n[\"math/bits\" on pkg.go.dev](https://pkg.go.dev/math/bits)", "url": "https://pkg.go.dev/math/bits", "path": "math/bits", "children": [] @@ -746,7 +826,7 @@ }, { "name": "rand", - "synopsis": "Package rand implements pseudo-random number generators unsuitable for\nsecurity-sensitive work.\n\nRandom numbers are generated by a Source. Top-level functions, such as\nFloat64 and Int, use a default shared Source that produces a deterministic\nsequence of values each time a program is run. Use the Seed function to\ninitialize the default Source if different behavior is required for each run.\nThe default Source is safe for concurrent use by multiple goroutines, but\nSources created by NewSource are not.\n\nThis package's outputs might be easily predictable regardless of how it's\nseeded. For random numbers suitable for security-sensitive work, see the\ncrypto/rand package.\n\n[\"math/rand\" on pkg.go.dev](https://pkg.go.dev/math/rand)", + "synopsis": "Package rand implements pseudo-random number generators suitable for tasks\nsuch as simulation, but it should not be used for security-sensitive work.\n\nRandom numbers are generated by a [Source], usually wrapped in a [Rand].\nBoth types should be used by a single goroutine at a time: sharing among\nmultiple goroutines requires some kind of synchronization.\n\nTop-level functions, such as [Float64] and [Int],\nare safe for concurrent use by multiple goroutines.\n\nThis package's outputs might be easily predictable regardless of how it's\nseeded. For random numbers suitable for security-sensitive work, see the\ncrypto/rand package.\n\n[\"math/rand\" on pkg.go.dev](https://pkg.go.dev/math/rand)", "url": "https://pkg.go.dev/math/rand", "path": "math/rand", "children": [] @@ -761,7 +841,7 @@ "children": [ { "name": "multipart", - "synopsis": "Package multipart implements MIME multipart parsing, as defined in RFC\n2046.\n\nThe implementation is sufficient for HTTP (RFC 2388) and the multipart\nbodies generated by popular browsers.\n\n[\"mime/multipart\" on pkg.go.dev](https://pkg.go.dev/mime/multipart)", + "synopsis": "Package multipart implements MIME multipart parsing, as defined in RFC\n2046.\n\nThe implementation is sufficient for HTTP (RFC 2388) and the multipart\nbodies generated by popular browsers.\n\n# Limits\n\nTo protect against malicious inputs, this package sets limits on the size\nof the MIME data it processes.\n\nReader.NextPart and Reader.NextRawPart limit the number of headers in a\npart to 10000 and Reader.ReadForm limits the total number of headers in all\nFileHeaders to 10000.\nThese limits may be adjusted with the GODEBUG=multipartmaxheaders=\u003cvalues\u003e\nsetting.\n\nReader.ReadForm further limits the number of parts in a form to 1000.\nThis limit may be adjusted with the GODEBUG=multipartmaxparts=\u003cvalue\u003e\nsetting.\n\nCopyright 2023 The Go Authors. All rights reserved.\nUse of this source code is governed by a BSD-style\nlicense that can be found in the LICENSE file.\n\n[\"mime/multipart\" on pkg.go.dev](https://pkg.go.dev/mime/multipart)", "url": "https://pkg.go.dev/mime/multipart", "path": "mime/multipart", "children": [] @@ -777,13 +857,13 @@ }, { "name": "net", - "synopsis": "Package net provides a portable interface for network I/O, including\nTCP/IP, UDP, domain name resolution, and Unix domain sockets.\n\nAlthough the package provides access to low-level networking\nprimitives, most clients will need only the basic interface provided\nby the Dial, Listen, and Accept functions and the associated\nConn and Listener interfaces. The crypto/tls package uses\nthe same interfaces and similar Dial and Listen functions.\n\nThe Dial function connects to a server:\n\n```\nconn, err := net.Dial(\"tcp\", \"golang.org:80\")\nif err != nil {\n\t// handle error\n}\nfmt.Fprintf(conn, \"GET / HTTP/1.0\\r\\n\\r\\n\")\nstatus, err := bufio.NewReader(conn).ReadString('\\n')\n// ...\n\n```\nThe Listen function creates servers:\n\n```\nln, err := net.Listen(\"tcp\", \":8080\")\nif err != nil {\n\t// handle error\n}\nfor {\n\tconn, err := ln.Accept()\n\tif err != nil {\n\t\t// handle error\n\t}\n\tgo handleConnection(conn)\n}\n\n```\nName Resolution\n\nThe method for resolving domain names, whether indirectly with functions like Dial\nor directly with functions like LookupHost and LookupAddr, varies by operating system.\n\nOn Unix systems, the resolver has two options for resolving names.\nIt can use a pure Go resolver that sends DNS requests directly to the servers\nlisted in /etc/resolv.conf, or it can use a cgo-based resolver that calls C\nlibrary routines such as getaddrinfo and getnameinfo.\n\nBy default the pure Go resolver is used, because a blocked DNS request consumes\nonly a goroutine, while a blocked C call consumes an operating system thread.\nWhen cgo is available, the cgo-based resolver is used instead under a variety of\nconditions: on systems that do not let programs make direct DNS requests (OS X),\nwhen the LOCALDOMAIN environment variable is present (even if empty),\nwhen the RES_OPTIONS or HOSTALIASES environment variable is non-empty,\nwhen the ASR_CONFIG environment variable is non-empty (OpenBSD only),\nwhen /etc/resolv.conf or /etc/nsswitch.conf specify the use of features that the\nGo resolver does not implement, and when the name being looked up ends in .local\nor is an mDNS name.\n\nThe resolver decision can be overridden by setting the netdns value of the\nGODEBUG environment variable (see package runtime) to go or cgo, as in:\n\n```\nexport GODEBUG=netdns=go # force pure Go resolver\nexport GODEBUG=netdns=cgo # force cgo resolver\n\n```\nThe decision can also be forced while building the Go source tree\nby setting the netgo or netcgo build tag.\n\nA numeric netdns setting, as in GODEBUG=netdns=1, causes the resolver\nto print debugging information about its decisions.\nTo force a particular resolver while also printing debugging information,\njoin the two settings by a plus sign, as in GODEBUG=netdns=go+1.\n\nOn Plan 9, the resolver always accesses /net/cs and /net/dns.\n\nOn Windows, the resolver always uses C library functions, such as GetAddrInfo and DnsQuery.\n\n[\"net\" on pkg.go.dev](https://pkg.go.dev/net)", + "synopsis": "Package net provides a portable interface for network I/O, including\nTCP/IP, UDP, domain name resolution, and Unix domain sockets.\n\nAlthough the package provides access to low-level networking\nprimitives, most clients will need only the basic interface provided\nby the Dial, Listen, and Accept functions and the associated\nConn and Listener interfaces. The crypto/tls package uses\nthe same interfaces and similar Dial and Listen functions.\n\nThe Dial function connects to a server:\n\n```\nconn, err := net.Dial(\"tcp\", \"golang.org:80\")\nif err != nil {\n\t// handle error\n}\nfmt.Fprintf(conn, \"GET / HTTP/1.0\\r\\n\\r\\n\")\nstatus, err := bufio.NewReader(conn).ReadString('\\n')\n// ...\n\n```\nThe Listen function creates servers:\n\n```\nln, err := net.Listen(\"tcp\", \":8080\")\nif err != nil {\n\t// handle error\n}\nfor {\n\tconn, err := ln.Accept()\n\tif err != nil {\n\t\t// handle error\n\t}\n\tgo handleConnection(conn)\n}\n\n```\n# Name Resolution\n\nThe method for resolving domain names, whether indirectly with functions like Dial\nor directly with functions like LookupHost and LookupAddr, varies by operating system.\n\nOn Unix systems, the resolver has two options for resolving names.\nIt can use a pure Go resolver that sends DNS requests directly to the servers\nlisted in /etc/resolv.conf, or it can use a cgo-based resolver that calls C\nlibrary routines such as getaddrinfo and getnameinfo.\n\nBy default the pure Go resolver is used, because a blocked DNS request consumes\nonly a goroutine, while a blocked C call consumes an operating system thread.\nWhen cgo is available, the cgo-based resolver is used instead under a variety of\nconditions: on systems that do not let programs make direct DNS requests (OS X),\nwhen the LOCALDOMAIN environment variable is present (even if empty),\nwhen the RES_OPTIONS or HOSTALIASES environment variable is non-empty,\nwhen the ASR_CONFIG environment variable is non-empty (OpenBSD only),\nwhen /etc/resolv.conf or /etc/nsswitch.conf specify the use of features that the\nGo resolver does not implement, and when the name being looked up ends in .local\nor is an mDNS name.\n\nThe resolver decision can be overridden by setting the netdns value of the\nGODEBUG environment variable (see package runtime) to go or cgo, as in:\n\n```\nexport GODEBUG=netdns=go # force pure Go resolver\nexport GODEBUG=netdns=cgo # force native resolver (cgo, win32)\n\n```\nThe decision can also be forced while building the Go source tree\nby setting the netgo or netcgo build tag.\n\nA numeric netdns setting, as in GODEBUG=netdns=1, causes the resolver\nto print debugging information about its decisions.\nTo force a particular resolver while also printing debugging information,\njoin the two settings by a plus sign, as in GODEBUG=netdns=go+1.\n\nOn macOS, if Go code that uses the net package is built with\n-buildmode=c-archive, linking the resulting archive into a C program\nrequires passing -lresolv when linking the C code.\n\nOn Plan 9, the resolver always accesses /net/cs and /net/dns.\n\nOn Windows, in Go 1.18.x and earlier, the resolver always used C\nlibrary functions, such as GetAddrInfo and DnsQuery.\n\n[\"net\" on pkg.go.dev](https://pkg.go.dev/net)", "url": "https://pkg.go.dev/net", "path": "net", "children": [ { "name": "http", - "synopsis": "Package http provides HTTP client and server implementations.\n\nGet, Head, Post, and PostForm make HTTP (or HTTPS) requests:\n\n```\nresp, err := http.Get(\"http://example.com/\")\n...\nresp, err := http.Post(\"http://example.com/upload\", \"image/jpeg\", \u0026buf)\n...\nresp, err := http.PostForm(\"http://example.com/form\",\n\turl.Values{\"key\": {\"Value\"}, \"id\": {\"123\"}})\n\n```\nThe client must close the response body when finished with it:\n\n```\nresp, err := http.Get(\"http://example.com/\")\nif err != nil {\n\t// handle error\n}\ndefer resp.Body.Close()\nbody, err := io.ReadAll(resp.Body)\n// ...\n\n```\nFor control over HTTP client headers, redirect policy, and other\nsettings, create a Client:\n\n```\nclient := \u0026http.Client{\n\tCheckRedirect: redirectPolicyFunc,\n}\n\nresp, err := client.Get(\"http://example.com\")\n// ...\n\nreq, err := http.NewRequest(\"GET\", \"http://example.com\", nil)\n// ...\nreq.Header.Add(\"If-None-Match\", `W/\"wyzzy\"`)\nresp, err := client.Do(req)\n// ...\n\n```\nFor control over proxies, TLS configuration, keep-alives,\ncompression, and other settings, create a Transport:\n\n```\ntr := \u0026http.Transport{\n\tMaxIdleConns: 10,\n\tIdleConnTimeout: 30 * time.Second,\n\tDisableCompression: true,\n}\nclient := \u0026http.Client{Transport: tr}\nresp, err := client.Get(\"https://example.com\")\n\n```\nClients and Transports are safe for concurrent use by multiple\ngoroutines and for efficiency should only be created once and re-used.\n\nListenAndServe starts an HTTP server with a given address and handler.\nThe handler is usually nil, which means to use DefaultServeMux.\nHandle and HandleFunc add handlers to DefaultServeMux:\n\n```\nhttp.Handle(\"/foo\", fooHandler)\n\nhttp.HandleFunc(\"/bar\", func(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"Hello, %q\", html.EscapeString(r.URL.Path))\n})\n\nlog.Fatal(http.ListenAndServe(\":8080\", nil))\n\n```\nMore control over the server's behavior is available by creating a\ncustom Server:\n\n```\ns := \u0026http.Server{\n\tAddr: \":8080\",\n\tHandler: myHandler,\n\tReadTimeout: 10 * time.Second,\n\tWriteTimeout: 10 * time.Second,\n\tMaxHeaderBytes: 1 \u003c\u003c 20,\n}\nlog.Fatal(s.ListenAndServe())\n\n```\nStarting with Go 1.6, the http package has transparent support for the\nHTTP/2 protocol when using HTTPS. Programs that must disable HTTP/2\ncan do so by setting Transport.TLSNextProto (for clients) or\nServer.TLSNextProto (for servers) to a non-nil, empty\nmap. Alternatively, the following GODEBUG environment variables are\ncurrently supported:\n\n```\nGODEBUG=http2client=0 # disable HTTP/2 client support\nGODEBUG=http2server=0 # disable HTTP/2 server support\nGODEBUG=http2debug=1 # enable verbose HTTP/2 debug logs\nGODEBUG=http2debug=2 # ... even more verbose, with frame dumps\n\n```\nThe GODEBUG variables are not covered by Go's API compatibility\npromise. Please report any issues before disabling HTTP/2\nsupport: https://golang.org/s/http2bug\n\nThe http package's Transport and Server both automatically enable\nHTTP/2 support for simple configurations. To enable HTTP/2 for more\ncomplex configurations, to use lower-level HTTP/2 features, or to use\na newer version of Go's http2 package, import \"golang.org/x/net/http2\"\ndirectly and use its ConfigureTransport and/or ConfigureServer\nfunctions. Manually configuring HTTP/2 via the golang.org/x/net/http2\npackage takes precedence over the net/http package's built-in HTTP/2\nsupport.\n\n[\"net/http\" on pkg.go.dev](https://pkg.go.dev/net/http)", + "synopsis": "Package http provides HTTP client and server implementations.\n\nGet, Head, Post, and PostForm make HTTP (or HTTPS) requests:\n\n```\nresp, err := http.Get(\"http://example.com/\")\n...\nresp, err := http.Post(\"http://example.com/upload\", \"image/jpeg\", \u0026buf)\n...\nresp, err := http.PostForm(\"http://example.com/form\",\n\turl.Values{\"key\": {\"Value\"}, \"id\": {\"123\"}})\n\n```\nThe caller must close the response body when finished with it:\n\n```\nresp, err := http.Get(\"http://example.com/\")\nif err != nil {\n\t// handle error\n}\ndefer resp.Body.Close()\nbody, err := io.ReadAll(resp.Body)\n// ...\n\n```\n# Clients and Transports\n\nFor control over HTTP client headers, redirect policy, and other\nsettings, create a Client:\n\n```\nclient := \u0026http.Client{\n\tCheckRedirect: redirectPolicyFunc,\n}\n\nresp, err := client.Get(\"http://example.com\")\n// ...\n\nreq, err := http.NewRequest(\"GET\", \"http://example.com\", nil)\n// ...\nreq.Header.Add(\"If-None-Match\", `W/\"wyzzy\"`)\nresp, err := client.Do(req)\n// ...\n\n```\nFor control over proxies, TLS configuration, keep-alives,\ncompression, and other settings, create a Transport:\n\n```\ntr := \u0026http.Transport{\n\tMaxIdleConns: 10,\n\tIdleConnTimeout: 30 * time.Second,\n\tDisableCompression: true,\n}\nclient := \u0026http.Client{Transport: tr}\nresp, err := client.Get(\"https://example.com\")\n\n```\nClients and Transports are safe for concurrent use by multiple\ngoroutines and for efficiency should only be created once and re-used.\n\n# Servers\n\nListenAndServe starts an HTTP server with a given address and handler.\nThe handler is usually nil, which means to use DefaultServeMux.\nHandle and HandleFunc add handlers to DefaultServeMux:\n\n```\nhttp.Handle(\"/foo\", fooHandler)\n\nhttp.HandleFunc(\"/bar\", func(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"Hello, %q\", html.EscapeString(r.URL.Path))\n})\n\nlog.Fatal(http.ListenAndServe(\":8080\", nil))\n\n```\nMore control over the server's behavior is available by creating a\ncustom Server:\n\n```\ns := \u0026http.Server{\n\tAddr: \":8080\",\n\tHandler: myHandler,\n\tReadTimeout: 10 * time.Second,\n\tWriteTimeout: 10 * time.Second,\n\tMaxHeaderBytes: 1 \u003c\u003c 20,\n}\nlog.Fatal(s.ListenAndServe())\n\n```\n# HTTP/2\n\nStarting with Go 1.6, the http package has transparent support for the\nHTTP/2 protocol when using HTTPS. Programs that must disable HTTP/2\ncan do so by setting Transport.TLSNextProto (for clients) or\nServer.TLSNextProto (for servers) to a non-nil, empty\nmap. Alternatively, the following GODEBUG settings are\ncurrently supported:\n\n```\nGODEBUG=http2client=0 # disable HTTP/2 client support\nGODEBUG=http2server=0 # disable HTTP/2 server support\nGODEBUG=http2debug=1 # enable verbose HTTP/2 debug logs\nGODEBUG=http2debug=2 # ... even more verbose, with frame dumps\n\n```\nPlease report any issues before disabling HTTP/2 support: https://golang.org/s/http2bug\n\nThe http package's Transport and Server both automatically enable\nHTTP/2 support for simple configurations. To enable HTTP/2 for more\ncomplex configurations, to use lower-level HTTP/2 features, or to use\na newer version of Go's http2 package, import \"golang.org/x/net/http2\"\ndirectly and use its ConfigureTransport and/or ConfigureServer\nfunctions. Manually configuring HTTP/2 via the golang.org/x/net/http2\npackage takes precedence over the net/http package's built-in HTTP/2\nsupport.\n\n[\"net/http\" on pkg.go.dev](https://pkg.go.dev/net/http)", "url": "https://pkg.go.dev/net/http", "path": "net/http", "children": [ @@ -831,7 +911,7 @@ }, { "name": "pprof", - "synopsis": "Package pprof serves via its HTTP server runtime profiling data\nin the format expected by the pprof visualization tool.\n\nThe package is typically only imported for the side effect of\nregistering its HTTP handlers.\nThe handled paths all begin with /debug/pprof/.\n\nTo use pprof, link this package into your program:\n```\nimport _ \"net/http/pprof\"\n\n```\nIf your application is not already running an http server, you\nneed to start one. Add \"net/http\" and \"log\" to your imports and\nthe following code to your main function:\n\n```\ngo func() {\n\tlog.Println(http.ListenAndServe(\"localhost:6060\", nil))\n}()\n\n```\nIf you are not using DefaultServeMux, you will have to register handlers\nwith the mux you are using.\n\nThen use the pprof tool to look at the heap profile:\n\n```\ngo tool pprof http://localhost:6060/debug/pprof/heap\n\n```\nOr to look at a 30-second CPU profile:\n\n```\ngo tool pprof http://localhost:6060/debug/pprof/profile?seconds=30\n\n```\nOr to look at the goroutine blocking profile, after calling\nruntime.SetBlockProfileRate in your program:\n\n```\ngo tool pprof http://localhost:6060/debug/pprof/block\n\n```\nOr to look at the holders of contended mutexes, after calling\nruntime.SetMutexProfileFraction in your program:\n\n```\ngo tool pprof http://localhost:6060/debug/pprof/mutex\n\n```\nThe package also exports a handler that serves execution trace data\nfor the \"go tool trace\" command. To collect a 5-second execution trace:\n\n```\ncurl -o trace.out http://localhost:6060/debug/pprof/trace?seconds=5\ngo tool trace trace.out\n\n```\nTo view all available profiles, open http://localhost:6060/debug/pprof/\nin your browser.\n\nFor a study of the facility in action, visit\n\n```\nhttps://blog.golang.org/2011/06/profiling-go-programs.html\n\n[\"net/http/pprof\" on pkg.go.dev](https://pkg.go.dev/net/http/pprof)", + "synopsis": "Package pprof serves via its HTTP server runtime profiling data\nin the format expected by the pprof visualization tool.\n\nThe package is typically only imported for the side effect of\nregistering its HTTP handlers.\nThe handled paths all begin with /debug/pprof/.\n\nTo use pprof, link this package into your program:\n\n```\nimport _ \"net/http/pprof\"\n\n```\nIf your application is not already running an http server, you\nneed to start one. Add \"net/http\" and \"log\" to your imports and\nthe following code to your main function:\n\n```\ngo func() {\n\tlog.Println(http.ListenAndServe(\"localhost:6060\", nil))\n}()\n\n```\nBy default, all the profiles listed in [runtime/pprof.Profile] are\navailable (via [Handler]), in addition to the [Cmdline], [Profile], [Symbol],\nand [Trace] profiles defined in this package.\nIf you are not using DefaultServeMux, you will have to register handlers\nwith the mux you are using.\n\n# Parameters\n\nParameters can be passed via GET query params:\n\n - debug=N (all profiles): response format: N = 0: binary (default), N \u003e 0: plaintext\n - gc=N (heap profile): N \u003e 0: run a garbage collection cycle before profiling\n - seconds=N (allocs, block, goroutine, heap, mutex, threadcreate profiles): return a delta profile\n - seconds=N (cpu (profile), trace profiles): profile for the given duration\n\n# Usage examples\n\nUse the pprof tool to look at the heap profile:\n\n```\ngo tool pprof http://localhost:6060/debug/pprof/heap\n\n```\nOr to look at a 30-second CPU profile:\n\n```\ngo tool pprof http://localhost:6060/debug/pprof/profile?seconds=30\n\n```\nOr to look at the goroutine blocking profile, after calling\nruntime.SetBlockProfileRate in your program:\n\n```\ngo tool pprof http://localhost:6060/debug/pprof/block\n\n```\nOr to look at the holders of contended mutexes, after calling\nruntime.SetMutexProfileFraction in your program:\n\n```\ngo tool pprof http://localhost:6060/debug/pprof/mutex\n\n```\nThe package also exports a handler that serves execution trace data\nfor the \"go tool trace\" command. To collect a 5-second execution trace:\n\n```\ncurl -o trace.out http://localhost:6060/debug/pprof/trace?seconds=5\ngo tool trace trace.out\n\n```\nTo view all available profiles, open http://localhost:6060/debug/pprof/\nin your browser.\n\nFor a study of the facility in action, visit\nhttps://blog.golang.org/2011/06/profiling-go-programs.html.\n\n[\"net/http/pprof\" on pkg.go.dev](https://pkg.go.dev/net/http/pprof)", "url": "https://pkg.go.dev/net/http/pprof", "path": "net/http/pprof", "children": [] @@ -840,21 +920,21 @@ }, { "name": "mail", - "synopsis": "Package mail implements parsing of mail messages.\n\nFor the most part, this package follows the syntax as specified by RFC 5322 and\nextended by RFC 6532.\nNotable divergences:\n```\n* Obsolete address formats are not parsed, including addresses with\n embedded route information.\n* The full range of spacing (the CFWS syntax element) is not supported,\n such as breaking addresses across lines.\n* No unicode normalization is performed.\n* The special characters ()[]:;@\\, are allowed to appear unquoted in names.\n\n[\"net/mail\" on pkg.go.dev](https://pkg.go.dev/net/mail)", + "synopsis": "Package mail implements parsing of mail messages.\n\nFor the most part, this package follows the syntax as specified by RFC 5322 and\nextended by RFC 6532.\nNotable divergences:\n - Obsolete address formats are not parsed, including addresses with\n embedded route information.\n - The full range of spacing (the CFWS syntax element) is not supported,\n such as breaking addresses across lines.\n - No unicode normalization is performed.\n - The special characters ()[]:;@\\, are allowed to appear unquoted in names.\n - A leading From line is permitted, as in mbox format (RFC 4155).\n\n[\"net/mail\" on pkg.go.dev](https://pkg.go.dev/net/mail)", "url": "https://pkg.go.dev/net/mail", "path": "net/mail", "children": [] }, { "name": "netip", - "synopsis": "Package netip defines an IP address type that's a small value type.\nBuilding on that Addr type, the package also defines AddrPort (an\nIP address and a port), and Prefix (an IP address and a bit length\nprefix).\n\nCompared to the net.IP type, this package's Addr type takes less\nmemory, is immutable, and is comparable (supports == and being a\nmap key).\n\n[\"net/netip\" on pkg.go.dev](https://pkg.go.dev/net/netip)", + "synopsis": "Package netip defines an IP address type that's a small value type.\nBuilding on that [Addr] type, the package also defines [AddrPort] (an\nIP address and a port) and [Prefix] (an IP address and a bit length\nprefix).\n\nCompared to the [net.IP] type, [Addr] type takes less memory, is immutable,\nand is comparable (supports == and being a map key).\n\n[\"net/netip\" on pkg.go.dev](https://pkg.go.dev/net/netip)", "url": "https://pkg.go.dev/net/netip", "path": "net/netip", "children": [] }, { "name": "rpc", - "synopsis": "```\nPackage rpc provides access to the exported methods of an object across a\nnetwork or other I/O connection. A server registers an object, making it visible\nas a service with the name of the type of the object. After registration, exported\nmethods of the object will be accessible remotely. A server may register multiple\nobjects (services) of different types but it is an error to register multiple\nobjects of the same type.\n\nOnly methods that satisfy these criteria will be made available for remote access;\nother methods will be ignored:\n\n\t- the method's type is exported.\n\t- the method is exported.\n\t- the method has two arguments, both exported (or builtin) types.\n\t- the method's second argument is a pointer.\n\t- the method has return type error.\n\nIn effect, the method must look schematically like\n\n\tfunc (t *T) MethodName(argType T1, replyType *T2) error\n\nwhere T1 and T2 can be marshaled by encoding/gob.\nThese requirements apply even if a different codec is used.\n(In the future, these requirements may soften for custom codecs.)\n\nThe method's first argument represents the arguments provided by the caller; the\nsecond argument represents the result parameters to be returned to the caller.\nThe method's return value, if non-nil, is passed back as a string that the client\nsees as if created by errors.New. If an error is returned, the reply parameter\nwill not be sent back to the client.\n\nThe server may handle requests on a single connection by calling ServeConn. More\ntypically it will create a network listener and call Accept or, for an HTTP\nlistener, HandleHTTP and http.Serve.\n\nA client wishing to use the service establishes a connection and then invokes\nNewClient on the connection. The convenience function Dial (DialHTTP) performs\nboth steps for a raw network connection (an HTTP connection). The resulting\nClient object has two methods, Call and Go, that specify the service and method to\ncall, a pointer containing the arguments, and a pointer to receive the result\nparameters.\n\nThe Call method waits for the remote call to complete while the Go method\nlaunches the call asynchronously and signals completion using the Call\nstructure's Done channel.\n\nUnless an explicit codec is set up, package encoding/gob is used to\ntransport the data.\n\nHere is a simple example. A server wishes to export an object of type Arith:\n\n\tpackage server\n\n\timport \"errors\"\n\n\ttype Args struct {\n\t\tA, B int\n\t}\n\n\ttype Quotient struct {\n\t\tQuo, Rem int\n\t}\n\n\ttype Arith int\n\n\tfunc (t *Arith) Multiply(args *Args, reply *int) error {\n\t\t*reply = args.A * args.B\n\t\treturn nil\n\t}\n\n\tfunc (t *Arith) Divide(args *Args, quo *Quotient) error {\n\t\tif args.B == 0 {\n\t\t\treturn errors.New(\"divide by zero\")\n\t\t}\n\t\tquo.Quo = args.A / args.B\n\t\tquo.Rem = args.A % args.B\n\t\treturn nil\n\t}\n\nThe server calls (for HTTP service):\n\n\tarith := new(Arith)\n\trpc.Register(arith)\n\trpc.HandleHTTP()\n\tl, e := net.Listen(\"tcp\", \":1234\")\n\tif e != nil {\n\t\tlog.Fatal(\"listen error:\", e)\n\t}\n\tgo http.Serve(l, nil)\n\nAt this point, clients can see a service \"Arith\" with methods \"Arith.Multiply\" and\n\"Arith.Divide\". To invoke one, a client first dials the server:\n\n\tclient, err := rpc.DialHTTP(\"tcp\", serverAddress + \":1234\")\n\tif err != nil {\n\t\tlog.Fatal(\"dialing:\", err)\n\t}\n\nThen it can make a remote call:\n\n\t// Synchronous call\n\targs := \u0026server.Args{7,8}\n\tvar reply int\n\terr = client.Call(\"Arith.Multiply\", args, \u0026reply)\n\tif err != nil {\n\t\tlog.Fatal(\"arith error:\", err)\n\t}\n\tfmt.Printf(\"Arith: %d*%d=%d\", args.A, args.B, reply)\n\nor\n\n\t// Asynchronous call\n\tquotient := new(Quotient)\n\tdivCall := client.Go(\"Arith.Divide\", args, quotient, nil)\n\treplyCall := \u003c-divCall.Done\t// will be equal to divCall\n\t// check errors, print, etc.\n\nA server implementation will often provide a simple, type-safe wrapper for the\nclient.\n\nThe net/rpc package is frozen and is not accepting new features.\n\n[\"net/rpc\" on pkg.go.dev](https://pkg.go.dev/net/rpc)", + "synopsis": "Package rpc provides access to the exported methods of an object across a\nnetwork or other I/O connection. A server registers an object, making it visible\nas a service with the name of the type of the object. After registration, exported\nmethods of the object will be accessible remotely. A server may register multiple\nobjects (services) of different types but it is an error to register multiple\nobjects of the same type.\n\nOnly methods that satisfy these criteria will be made available for remote access;\nother methods will be ignored:\n\n - the method's type is exported.\n - the method is exported.\n - the method has two arguments, both exported (or builtin) types.\n - the method's second argument is a pointer.\n - the method has return type error.\n\nIn effect, the method must look schematically like\n\n```\nfunc (t *T) MethodName(argType T1, replyType *T2) error\n\n```\nwhere T1 and T2 can be marshaled by encoding/gob.\nThese requirements apply even if a different codec is used.\n(In the future, these requirements may soften for custom codecs.)\n\nThe method's first argument represents the arguments provided by the caller; the\nsecond argument represents the result parameters to be returned to the caller.\nThe method's return value, if non-nil, is passed back as a string that the client\nsees as if created by errors.New. If an error is returned, the reply parameter\nwill not be sent back to the client.\n\nThe server may handle requests on a single connection by calling ServeConn. More\ntypically it will create a network listener and call Accept or, for an HTTP\nlistener, HandleHTTP and http.Serve.\n\nA client wishing to use the service establishes a connection and then invokes\nNewClient on the connection. The convenience function Dial (DialHTTP) performs\nboth steps for a raw network connection (an HTTP connection). The resulting\nClient object has two methods, Call and Go, that specify the service and method to\ncall, a pointer containing the arguments, and a pointer to receive the result\nparameters.\n\nThe Call method waits for the remote call to complete while the Go method\nlaunches the call asynchronously and signals completion using the Call\nstructure's Done channel.\n\nUnless an explicit codec is set up, package encoding/gob is used to\ntransport the data.\n\nHere is a simple example. A server wishes to export an object of type Arith:\n\n```\npackage server\n\nimport \"errors\"\n\ntype Args struct {\n\tA, B int\n}\n\ntype Quotient struct {\n\tQuo, Rem int\n}\n\ntype Arith int\n\nfunc (t *Arith) Multiply(args *Args, reply *int) error {\n\t*reply = args.A * args.B\n\treturn nil\n}\n\nfunc (t *Arith) Divide(args *Args, quo *Quotient) error {\n\tif args.B == 0 {\n\t\treturn errors.New(\"divide by zero\")\n\t}\n\tquo.Quo = args.A / args.B\n\tquo.Rem = args.A % args.B\n\treturn nil\n}\n\n```\nThe server calls (for HTTP service):\n\n```\narith := new(Arith)\nrpc.Register(arith)\nrpc.HandleHTTP()\nl, err := net.Listen(\"tcp\", \":1234\")\nif err != nil {\n\tlog.Fatal(\"listen error:\", err)\n}\ngo http.Serve(l, nil)\n\n```\nAt this point, clients can see a service \"Arith\" with methods \"Arith.Multiply\" and\n\"Arith.Divide\". To invoke one, a client first dials the server:\n\n```\nclient, err := rpc.DialHTTP(\"tcp\", serverAddress + \":1234\")\nif err != nil {\n\tlog.Fatal(\"dialing:\", err)\n}\n\n```\nThen it can make a remote call:\n\n```\n// Synchronous call\nargs := \u0026server.Args{7,8}\nvar reply int\nerr = client.Call(\"Arith.Multiply\", args, \u0026reply)\nif err != nil {\n\tlog.Fatal(\"arith error:\", err)\n}\nfmt.Printf(\"Arith: %d*%d=%d\", args.A, args.B, reply)\n\n```\nor\n\n```\n// Asynchronous call\nquotient := new(Quotient)\ndivCall := client.Go(\"Arith.Divide\", args, quotient, nil)\nreplyCall := \u003c-divCall.Done\t// will be equal to divCall\n// check errors, print, etc.\n\n```\nA server implementation will often provide a simple, type-safe wrapper for the\nclient.\n\nThe net/rpc package is frozen and is not accepting new features.\n\n[\"net/rpc\" on pkg.go.dev](https://pkg.go.dev/net/rpc)", "url": "https://pkg.go.dev/net/rpc", "path": "net/rpc", "children": [ @@ -869,7 +949,7 @@ }, { "name": "smtp", - "synopsis": "Package smtp implements the Simple Mail Transfer Protocol as defined in RFC 5321.\nIt also implements the following extensions:\n```\n8BITMIME RFC 1652\nAUTH RFC 2554\nSTARTTLS RFC 3207\n```\nAdditional extensions may be handled by clients.\n\nThe smtp package is frozen and is not accepting new features.\nSome external packages provide more functionality. See:\n\n https://godoc.org/?q=smtp\n\n[\"net/smtp\" on pkg.go.dev](https://pkg.go.dev/net/smtp)", + "synopsis": "Package smtp implements the Simple Mail Transfer Protocol as defined in RFC 5321.\nIt also implements the following extensions:\n\n```\n8BITMIME RFC 1652\nAUTH RFC 2554\nSTARTTLS RFC 3207\n\n```\nAdditional extensions may be handled by clients.\n\nThe smtp package is frozen and is not accepting new features.\nSome external packages provide more functionality. See:\n\n```\nhttps://godoc.org/?q=smtp\n\n[\"net/smtp\" on pkg.go.dev](https://pkg.go.dev/net/smtp)", "url": "https://pkg.go.dev/net/smtp", "path": "net/smtp", "children": [] @@ -898,14 +978,14 @@ "children": [ { "name": "exec", - "synopsis": "Package exec runs external commands. It wraps os.StartProcess to make it\neasier to remap stdin and stdout, connect I/O with pipes, and do other\nadjustments.\n\nUnlike the \"system\" library call from C and other languages, the\nos/exec package intentionally does not invoke the system shell and\ndoes not expand any glob patterns or handle other expansions,\npipelines, or redirections typically done by shells. The package\nbehaves more like C's \"exec\" family of functions. To expand glob\npatterns, either call the shell directly, taking care to escape any\ndangerous input, or use the path/filepath package's Glob function.\nTo expand environment variables, use package os's ExpandEnv.\n\nNote that the examples in this package assume a Unix system.\nThey may not run on Windows, and they do not run in the Go Playground\nused by golang.org and godoc.org.\n\n[\"os/exec\" on pkg.go.dev](https://pkg.go.dev/os/exec)", + "synopsis": "Package exec runs external commands. It wraps os.StartProcess to make it\neasier to remap stdin and stdout, connect I/O with pipes, and do other\nadjustments.\n\nUnlike the \"system\" library call from C and other languages, the\nos/exec package intentionally does not invoke the system shell and\ndoes not expand any glob patterns or handle other expansions,\npipelines, or redirections typically done by shells. The package\nbehaves more like C's \"exec\" family of functions. To expand glob\npatterns, either call the shell directly, taking care to escape any\ndangerous input, or use the path/filepath package's Glob function.\nTo expand environment variables, use package os's ExpandEnv.\n\nNote that the examples in this package assume a Unix system.\nThey may not run on Windows, and they do not run in the Go Playground\nused by golang.org and godoc.org.\n\n# Executables in the current directory\n\nThe functions Command and LookPath look for a program\nin the directories listed in the current path, following the\nconventions of the host operating system.\nOperating systems have for decades included the current\ndirectory in this search, sometimes implicitly and sometimes\nconfigured explicitly that way by default.\nModern practice is that including the current directory\nis usually unexpected and often leads to security problems.\n\nTo avoid those security problems, as of Go 1.19, this package will not resolve a program\nusing an implicit or explicit path entry relative to the current directory.\nThat is, if you run exec.LookPath(\"go\"), it will not successfully return\n./go on Unix nor .\\go.exe on Windows, no matter how the path is configured.\nInstead, if the usual path algorithms would result in that answer,\nthese functions return an error err satisfying errors.Is(err, ErrDot).\n\nFor example, consider these two program snippets:\n\n```\npath, err := exec.LookPath(\"prog\")\nif err != nil {\n\tlog.Fatal(err)\n}\nuse(path)\n\n```\nand\n\n```\ncmd := exec.Command(\"prog\")\nif err := cmd.Run(); err != nil {\n\tlog.Fatal(err)\n}\n\n```\nThese will not find and run ./prog or .\\prog.exe,\nno matter how the current path is configured.\n\nCode that always wants to run a program from the current directory\ncan be rewritten to say \"./prog\" instead of \"prog\".\n\nCode that insists on including results from relative path entries\ncan instead override the error using an errors.Is check:\n\n```\npath, err := exec.LookPath(\"prog\")\nif errors.Is(err, exec.ErrDot) {\n\terr = nil\n}\nif err != nil {\n\tlog.Fatal(err)\n}\nuse(path)\n\n```\nand\n\n```\ncmd := exec.Command(\"prog\")\nif errors.Is(cmd.Err, exec.ErrDot) {\n\tcmd.Err = nil\n}\nif err := cmd.Run(); err != nil {\n\tlog.Fatal(err)\n}\n\n```\nSetting the environment variable GODEBUG=execerrdot=0\ndisables generation of ErrDot entirely, temporarily restoring the pre-Go 1.19\nbehavior for programs that are unable to apply more targeted fixes.\nA future version of Go may remove support for this variable.\n\nBefore adding such overrides, make sure you understand the\nsecurity implications of doing so.\nSee https://go.dev/blog/path-security for more information.\n\n[\"os/exec\" on pkg.go.dev](https://pkg.go.dev/os/exec)", "url": "https://pkg.go.dev/os/exec", "path": "os/exec", "children": [] }, { "name": "signal", - "synopsis": "Package signal implements access to incoming signals.\n\nSignals are primarily used on Unix-like systems. For the use of this\npackage on Windows and Plan 9, see below.\n\nTypes of signals\n\nThe signals SIGKILL and SIGSTOP may not be caught by a program, and\ntherefore cannot be affected by this package.\n\nSynchronous signals are signals triggered by errors in program\nexecution: SIGBUS, SIGFPE, and SIGSEGV. These are only considered\nsynchronous when caused by program execution, not when sent using\nos.Process.Kill or the kill program or some similar mechanism. In\ngeneral, except as discussed below, Go programs will convert a\nsynchronous signal into a run-time panic.\n\nThe remaining signals are asynchronous signals. They are not\ntriggered by program errors, but are instead sent from the kernel or\nfrom some other program.\n\nOf the asynchronous signals, the SIGHUP signal is sent when a program\nloses its controlling terminal. The SIGINT signal is sent when the\nuser at the controlling terminal presses the interrupt character,\nwhich by default is ^C (Control-C). The SIGQUIT signal is sent when\nthe user at the controlling terminal presses the quit character, which\nby default is ^\\ (Control-Backslash). In general you can cause a\nprogram to simply exit by pressing ^C, and you can cause it to exit\nwith a stack dump by pressing ^\\.\n\nDefault behavior of signals in Go programs\n\nBy default, a synchronous signal is converted into a run-time panic. A\nSIGHUP, SIGINT, or SIGTERM signal causes the program to exit. A\nSIGQUIT, SIGILL, SIGTRAP, SIGABRT, SIGSTKFLT, SIGEMT, or SIGSYS signal\ncauses the program to exit with a stack dump. A SIGTSTP, SIGTTIN, or\nSIGTTOU signal gets the system default behavior (these signals are\nused by the shell for job control). The SIGPROF signal is handled\ndirectly by the Go runtime to implement runtime.CPUProfile. Other\nsignals will be caught but no action will be taken.\n\nIf the Go program is started with either SIGHUP or SIGINT ignored\n(signal handler set to SIG_IGN), they will remain ignored.\n\nIf the Go program is started with a non-empty signal mask, that will\ngenerally be honored. However, some signals are explicitly unblocked:\nthe synchronous signals, SIGILL, SIGTRAP, SIGSTKFLT, SIGCHLD, SIGPROF,\nand, on Linux, signals 32 (SIGCANCEL) and 33 (SIGSETXID)\n(SIGCANCEL and SIGSETXID are used internally by glibc). Subprocesses\nstarted by os.Exec, or by the os/exec package, will inherit the\nmodified signal mask.\n\nChanging the behavior of signals in Go programs\n\nThe functions in this package allow a program to change the way Go\nprograms handle signals.\n\nNotify disables the default behavior for a given set of asynchronous\nsignals and instead delivers them over one or more registered\nchannels. Specifically, it applies to the signals SIGHUP, SIGINT,\nSIGQUIT, SIGABRT, and SIGTERM. It also applies to the job control\nsignals SIGTSTP, SIGTTIN, and SIGTTOU, in which case the system\ndefault behavior does not occur. It also applies to some signals that\notherwise cause no action: SIGUSR1, SIGUSR2, SIGPIPE, SIGALRM,\nSIGCHLD, SIGCONT, SIGURG, SIGXCPU, SIGXFSZ, SIGVTALRM, SIGWINCH,\nSIGIO, SIGPWR, SIGSYS, SIGINFO, SIGTHR, SIGWAITING, SIGLWP, SIGFREEZE,\nSIGTHAW, SIGLOST, SIGXRES, SIGJVM1, SIGJVM2, and any real time signals\nused on the system. Note that not all of these signals are available\non all systems.\n\nIf the program was started with SIGHUP or SIGINT ignored, and Notify\nis called for either signal, a signal handler will be installed for\nthat signal and it will no longer be ignored. If, later, Reset or\nIgnore is called for that signal, or Stop is called on all channels\npassed to Notify for that signal, the signal will once again be\nignored. Reset will restore the system default behavior for the\nsignal, while Ignore will cause the system to ignore the signal\nentirely.\n\nIf the program is started with a non-empty signal mask, some signals\nwill be explicitly unblocked as described above. If Notify is called\nfor a blocked signal, it will be unblocked. If, later, Reset is\ncalled for that signal, or Stop is called on all channels passed to\nNotify for that signal, the signal will once again be blocked.\n\nSIGPIPE\n\nWhen a Go program writes to a broken pipe, the kernel will raise a\nSIGPIPE signal.\n\nIf the program has not called Notify to receive SIGPIPE signals, then\nthe behavior depends on the file descriptor number. A write to a\nbroken pipe on file descriptors 1 or 2 (standard output or standard\nerror) will cause the program to exit with a SIGPIPE signal. A write\nto a broken pipe on some other file descriptor will take no action on\nthe SIGPIPE signal, and the write will fail with an EPIPE error.\n\nIf the program has called Notify to receive SIGPIPE signals, the file\ndescriptor number does not matter. The SIGPIPE signal will be\ndelivered to the Notify channel, and the write will fail with an EPIPE\nerror.\n\nThis means that, by default, command line programs will behave like\ntypical Unix command line programs, while other programs will not\ncrash with SIGPIPE when writing to a closed network connection.\n\nGo programs that use cgo or SWIG\n\nIn a Go program that includes non-Go code, typically C/C++ code\naccessed using cgo or SWIG, Go's startup code normally runs first. It\nconfigures the signal handlers as expected by the Go runtime, before\nthe non-Go startup code runs. If the non-Go startup code wishes to\ninstall its own signal handlers, it must take certain steps to keep Go\nworking well. This section documents those steps and the overall\neffect changes to signal handler settings by the non-Go code can have\non Go programs. In rare cases, the non-Go code may run before the Go\ncode, in which case the next section also applies.\n\nIf the non-Go code called by the Go program does not change any signal\nhandlers or masks, then the behavior is the same as for a pure Go\nprogram.\n\nIf the non-Go code installs any signal handlers, it must use the\nSA_ONSTACK flag with sigaction. Failing to do so is likely to cause\nthe program to crash if the signal is received. Go programs routinely\nrun with a limited stack, and therefore set up an alternate signal\nstack.\n\nIf the non-Go code installs a signal handler for any of the\nsynchronous signals (SIGBUS, SIGFPE, SIGSEGV), then it should record\nthe existing Go signal handler. If those signals occur while\nexecuting Go code, it should invoke the Go signal handler (whether the\nsignal occurs while executing Go code can be determined by looking at\nthe PC passed to the signal handler). Otherwise some Go run-time\npanics will not occur as expected.\n\nIf the non-Go code installs a signal handler for any of the\nasynchronous signals, it may invoke the Go signal handler or not as it\nchooses. Naturally, if it does not invoke the Go signal handler, the\nGo behavior described above will not occur. This can be an issue with\nthe SIGPROF signal in particular.\n\nThe non-Go code should not change the signal mask on any threads\ncreated by the Go runtime. If the non-Go code starts new threads of\nits own, it may set the signal mask as it pleases.\n\nIf the non-Go code starts a new thread, changes the signal mask, and\nthen invokes a Go function in that thread, the Go runtime will\nautomatically unblock certain signals: the synchronous signals,\nSIGILL, SIGTRAP, SIGSTKFLT, SIGCHLD, SIGPROF, SIGCANCEL, and\nSIGSETXID. When the Go function returns, the non-Go signal mask will\nbe restored.\n\nIf the Go signal handler is invoked on a non-Go thread not running Go\ncode, the handler generally forwards the signal to the non-Go code, as\nfollows. If the signal is SIGPROF, the Go handler does\nnothing. Otherwise, the Go handler removes itself, unblocks the\nsignal, and raises it again, to invoke any non-Go handler or default\nsystem handler. If the program does not exit, the Go handler then\nreinstalls itself and continues execution of the program.\n\nNon-Go programs that call Go code\n\nWhen Go code is built with options like -buildmode=c-shared, it will\nbe run as part of an existing non-Go program. The non-Go code may\nhave already installed signal handlers when the Go code starts (that\nmay also happen in unusual cases when using cgo or SWIG; in that case,\nthe discussion here applies). For -buildmode=c-archive the Go runtime\nwill initialize signals at global constructor time. For\n-buildmode=c-shared the Go runtime will initialize signals when the\nshared library is loaded.\n\nIf the Go runtime sees an existing signal handler for the SIGCANCEL or\nSIGSETXID signals (which are used only on Linux), it will turn on\nthe SA_ONSTACK flag and otherwise keep the signal handler.\n\nFor the synchronous signals and SIGPIPE, the Go runtime will install a\nsignal handler. It will save any existing signal handler. If a\nsynchronous signal arrives while executing non-Go code, the Go runtime\nwill invoke the existing signal handler instead of the Go signal\nhandler.\n\nGo code built with -buildmode=c-archive or -buildmode=c-shared will\nnot install any other signal handlers by default. If there is an\nexisting signal handler, the Go runtime will turn on the SA_ONSTACK\nflag and otherwise keep the signal handler. If Notify is called for an\nasynchronous signal, a Go signal handler will be installed for that\nsignal. If, later, Reset is called for that signal, the original\nhandling for that signal will be reinstalled, restoring the non-Go\nsignal handler if any.\n\nGo code built without -buildmode=c-archive or -buildmode=c-shared will\ninstall a signal handler for the asynchronous signals listed above,\nand save any existing signal handler. If a signal is delivered to a\nnon-Go thread, it will act as described above, except that if there is\nan existing non-Go signal handler, that handler will be installed\nbefore raising the signal.\n\nWindows\n\nOn Windows a ^C (Control-C) or ^BREAK (Control-Break) normally cause\nthe program to exit. If Notify is called for os.Interrupt, ^C or ^BREAK\nwill cause os.Interrupt to be sent on the channel, and the program will\nnot exit. If Reset is called, or Stop is called on all channels passed\nto Notify, then the default behavior will be restored.\n\nAdditionally, if Notify is called, and Windows sends CTRL_CLOSE_EVENT,\nCTRL_LOGOFF_EVENT or CTRL_SHUTDOWN_EVENT to the process, Notify will\nreturn syscall.SIGTERM. Unlike Control-C and Control-Break, Notify does\nnot change process behavior when either CTRL_CLOSE_EVENT,\nCTRL_LOGOFF_EVENT or CTRL_SHUTDOWN_EVENT is received - the process will\nstill get terminated unless it exits. But receiving syscall.SIGTERM will\ngive the process an opportunity to clean up before termination.\n\nPlan 9\n\nOn Plan 9, signals have type syscall.Note, which is a string. Calling\nNotify with a syscall.Note will cause that value to be sent on the\nchannel when that string is posted as a note.\n\n[\"os/signal\" on pkg.go.dev](https://pkg.go.dev/os/signal)", + "synopsis": "Package signal implements access to incoming signals.\n\nSignals are primarily used on Unix-like systems. For the use of this\npackage on Windows and Plan 9, see below.\n\n# Types of signals\n\nThe signals SIGKILL and SIGSTOP may not be caught by a program, and\ntherefore cannot be affected by this package.\n\nSynchronous signals are signals triggered by errors in program\nexecution: SIGBUS, SIGFPE, and SIGSEGV. These are only considered\nsynchronous when caused by program execution, not when sent using\n[os.Process.Kill] or the kill program or some similar mechanism. In\ngeneral, except as discussed below, Go programs will convert a\nsynchronous signal into a run-time panic.\n\nThe remaining signals are asynchronous signals. They are not\ntriggered by program errors, but are instead sent from the kernel or\nfrom some other program.\n\nOf the asynchronous signals, the SIGHUP signal is sent when a program\nloses its controlling terminal. The SIGINT signal is sent when the\nuser at the controlling terminal presses the interrupt character,\nwhich by default is ^C (Control-C). The SIGQUIT signal is sent when\nthe user at the controlling terminal presses the quit character, which\nby default is ^\\ (Control-Backslash). In general you can cause a\nprogram to simply exit by pressing ^C, and you can cause it to exit\nwith a stack dump by pressing ^\\.\n\n# Default behavior of signals in Go programs\n\nBy default, a synchronous signal is converted into a run-time panic. A\nSIGHUP, SIGINT, or SIGTERM signal causes the program to exit. A\nSIGQUIT, SIGILL, SIGTRAP, SIGABRT, SIGSTKFLT, SIGEMT, or SIGSYS signal\ncauses the program to exit with a stack dump. A SIGTSTP, SIGTTIN, or\nSIGTTOU signal gets the system default behavior (these signals are\nused by the shell for job control). The SIGPROF signal is handled\ndirectly by the Go runtime to implement runtime.CPUProfile. Other\nsignals will be caught but no action will be taken.\n\nIf the Go program is started with either SIGHUP or SIGINT ignored\n(signal handler set to SIG_IGN), they will remain ignored.\n\nIf the Go program is started with a non-empty signal mask, that will\ngenerally be honored. However, some signals are explicitly unblocked:\nthe synchronous signals, SIGILL, SIGTRAP, SIGSTKFLT, SIGCHLD, SIGPROF,\nand, on Linux, signals 32 (SIGCANCEL) and 33 (SIGSETXID)\n(SIGCANCEL and SIGSETXID are used internally by glibc). Subprocesses\nstarted by [os.Exec], or by [os/exec], will inherit the\nmodified signal mask.\n\n# Changing the behavior of signals in Go programs\n\nThe functions in this package allow a program to change the way Go\nprograms handle signals.\n\nNotify disables the default behavior for a given set of asynchronous\nsignals and instead delivers them over one or more registered\nchannels. Specifically, it applies to the signals SIGHUP, SIGINT,\nSIGQUIT, SIGABRT, and SIGTERM. It also applies to the job control\nsignals SIGTSTP, SIGTTIN, and SIGTTOU, in which case the system\ndefault behavior does not occur. It also applies to some signals that\notherwise cause no action: SIGUSR1, SIGUSR2, SIGPIPE, SIGALRM,\nSIGCHLD, SIGCONT, SIGURG, SIGXCPU, SIGXFSZ, SIGVTALRM, SIGWINCH,\nSIGIO, SIGPWR, SIGSYS, SIGINFO, SIGTHR, SIGWAITING, SIGLWP, SIGFREEZE,\nSIGTHAW, SIGLOST, SIGXRES, SIGJVM1, SIGJVM2, and any real time signals\nused on the system. Note that not all of these signals are available\non all systems.\n\nIf the program was started with SIGHUP or SIGINT ignored, and Notify\nis called for either signal, a signal handler will be installed for\nthat signal and it will no longer be ignored. If, later, Reset or\nIgnore is called for that signal, or Stop is called on all channels\npassed to Notify for that signal, the signal will once again be\nignored. Reset will restore the system default behavior for the\nsignal, while Ignore will cause the system to ignore the signal\nentirely.\n\nIf the program is started with a non-empty signal mask, some signals\nwill be explicitly unblocked as described above. If Notify is called\nfor a blocked signal, it will be unblocked. If, later, Reset is\ncalled for that signal, or Stop is called on all channels passed to\nNotify for that signal, the signal will once again be blocked.\n\n# SIGPIPE\n\nWhen a Go program writes to a broken pipe, the kernel will raise a\nSIGPIPE signal.\n\nIf the program has not called Notify to receive SIGPIPE signals, then\nthe behavior depends on the file descriptor number. A write to a\nbroken pipe on file descriptors 1 or 2 (standard output or standard\nerror) will cause the program to exit with a SIGPIPE signal. A write\nto a broken pipe on some other file descriptor will take no action on\nthe SIGPIPE signal, and the write will fail with an EPIPE error.\n\nIf the program has called Notify to receive SIGPIPE signals, the file\ndescriptor number does not matter. The SIGPIPE signal will be\ndelivered to the Notify channel, and the write will fail with an EPIPE\nerror.\n\nThis means that, by default, command line programs will behave like\ntypical Unix command line programs, while other programs will not\ncrash with SIGPIPE when writing to a closed network connection.\n\n# Go programs that use cgo or SWIG\n\nIn a Go program that includes non-Go code, typically C/C++ code\naccessed using cgo or SWIG, Go's startup code normally runs first. It\nconfigures the signal handlers as expected by the Go runtime, before\nthe non-Go startup code runs. If the non-Go startup code wishes to\ninstall its own signal handlers, it must take certain steps to keep Go\nworking well. This section documents those steps and the overall\neffect changes to signal handler settings by the non-Go code can have\non Go programs. In rare cases, the non-Go code may run before the Go\ncode, in which case the next section also applies.\n\nIf the non-Go code called by the Go program does not change any signal\nhandlers or masks, then the behavior is the same as for a pure Go\nprogram.\n\nIf the non-Go code installs any signal handlers, it must use the\nSA_ONSTACK flag with sigaction. Failing to do so is likely to cause\nthe program to crash if the signal is received. Go programs routinely\nrun with a limited stack, and therefore set up an alternate signal\nstack.\n\nIf the non-Go code installs a signal handler for any of the\nsynchronous signals (SIGBUS, SIGFPE, SIGSEGV), then it should record\nthe existing Go signal handler. If those signals occur while\nexecuting Go code, it should invoke the Go signal handler (whether the\nsignal occurs while executing Go code can be determined by looking at\nthe PC passed to the signal handler). Otherwise some Go run-time\npanics will not occur as expected.\n\nIf the non-Go code installs a signal handler for any of the\nasynchronous signals, it may invoke the Go signal handler or not as it\nchooses. Naturally, if it does not invoke the Go signal handler, the\nGo behavior described above will not occur. This can be an issue with\nthe SIGPROF signal in particular.\n\nThe non-Go code should not change the signal mask on any threads\ncreated by the Go runtime. If the non-Go code starts new threads of\nits own, it may set the signal mask as it pleases.\n\nIf the non-Go code starts a new thread, changes the signal mask, and\nthen invokes a Go function in that thread, the Go runtime will\nautomatically unblock certain signals: the synchronous signals,\nSIGILL, SIGTRAP, SIGSTKFLT, SIGCHLD, SIGPROF, SIGCANCEL, and\nSIGSETXID. When the Go function returns, the non-Go signal mask will\nbe restored.\n\nIf the Go signal handler is invoked on a non-Go thread not running Go\ncode, the handler generally forwards the signal to the non-Go code, as\nfollows. If the signal is SIGPROF, the Go handler does\nnothing. Otherwise, the Go handler removes itself, unblocks the\nsignal, and raises it again, to invoke any non-Go handler or default\nsystem handler. If the program does not exit, the Go handler then\nreinstalls itself and continues execution of the program.\n\nIf a SIGPIPE signal is received, the Go program will invoke the\nspecial handling described above if the SIGPIPE is received on a Go\nthread. If the SIGPIPE is received on a non-Go thread the signal will\nbe forwarded to the non-Go handler, if any; if there is none the\ndefault system handler will cause the program to terminate.\n\n# Non-Go programs that call Go code\n\nWhen Go code is built with options like -buildmode=c-shared, it will\nbe run as part of an existing non-Go program. The non-Go code may\nhave already installed signal handlers when the Go code starts (that\nmay also happen in unusual cases when using cgo or SWIG; in that case,\nthe discussion here applies). For -buildmode=c-archive the Go runtime\nwill initialize signals at global constructor time. For\n-buildmode=c-shared the Go runtime will initialize signals when the\nshared library is loaded.\n\nIf the Go runtime sees an existing signal handler for the SIGCANCEL or\nSIGSETXID signals (which are used only on Linux), it will turn on\nthe SA_ONSTACK flag and otherwise keep the signal handler.\n\nFor the synchronous signals and SIGPIPE, the Go runtime will install a\nsignal handler. It will save any existing signal handler. If a\nsynchronous signal arrives while executing non-Go code, the Go runtime\nwill invoke the existing signal handler instead of the Go signal\nhandler.\n\nGo code built with -buildmode=c-archive or -buildmode=c-shared will\nnot install any other signal handlers by default. If there is an\nexisting signal handler, the Go runtime will turn on the SA_ONSTACK\nflag and otherwise keep the signal handler. If Notify is called for an\nasynchronous signal, a Go signal handler will be installed for that\nsignal. If, later, Reset is called for that signal, the original\nhandling for that signal will be reinstalled, restoring the non-Go\nsignal handler if any.\n\nGo code built without -buildmode=c-archive or -buildmode=c-shared will\ninstall a signal handler for the asynchronous signals listed above,\nand save any existing signal handler. If a signal is delivered to a\nnon-Go thread, it will act as described above, except that if there is\nan existing non-Go signal handler, that handler will be installed\nbefore raising the signal.\n\n# Windows\n\nOn Windows a ^C (Control-C) or ^BREAK (Control-Break) normally cause\nthe program to exit. If Notify is called for [os.Interrupt], ^C or ^BREAK\nwill cause [os.Interrupt] to be sent on the channel, and the program will\nnot exit. If Reset is called, or Stop is called on all channels passed\nto Notify, then the default behavior will be restored.\n\nAdditionally, if Notify is called, and Windows sends CTRL_CLOSE_EVENT,\nCTRL_LOGOFF_EVENT or CTRL_SHUTDOWN_EVENT to the process, Notify will\nreturn syscall.SIGTERM. Unlike Control-C and Control-Break, Notify does\nnot change process behavior when either CTRL_CLOSE_EVENT,\nCTRL_LOGOFF_EVENT or CTRL_SHUTDOWN_EVENT is received - the process will\nstill get terminated unless it exits. But receiving syscall.SIGTERM will\ngive the process an opportunity to clean up before termination.\n\n# Plan 9\n\nOn Plan 9, signals have type syscall.Note, which is a string. Calling\nNotify with a syscall.Note will cause that value to be sent on the\nchannel when that string is posted as a note.\n\n[\"os/signal\" on pkg.go.dev](https://pkg.go.dev/os/signal)", "url": "https://pkg.go.dev/os/signal", "path": "os/signal", "children": [] @@ -927,7 +1007,7 @@ "children": [ { "name": "filepath", - "synopsis": "Package filepath implements utility routines for manipulating filename paths\nin a way compatible with the target operating system-defined file paths.\n\nThe filepath package uses either forward slashes or backslashes,\ndepending on the operating system. To process paths such as URLs\nthat always use forward slashes regardless of the operating\nsystem, see the path package.\n\n[\"path/filepath\" on pkg.go.dev](https://pkg.go.dev/path/filepath)", + "synopsis": "Package filepath implements utility routines for manipulating filename paths\nin a way compatible with the target operating system-defined file paths.\n\nThe filepath package uses either forward slashes or backslashes,\ndepending on the operating system. To process paths such as URLs\nthat always use forward slashes regardless of the operating\nsystem, see the [path] package.\n\n[\"path/filepath\" on pkg.go.dev](https://pkg.go.dev/path/filepath)", "url": "https://pkg.go.dev/path/filepath", "path": "path/filepath", "children": [] @@ -936,7 +1016,7 @@ }, { "name": "plugin", - "synopsis": "Package plugin implements loading and symbol resolution of Go plugins.\n\nA plugin is a Go main package with exported functions and variables that\nhas been built with:\n\n```\ngo build -buildmode=plugin\n\n```\nWhen a plugin is first opened, the init functions of all packages not\nalready part of the program are called. The main function is not run.\nA plugin is only initialized once, and cannot be closed.\n\nCurrently plugins are only supported on Linux, FreeBSD, and macOS.\nPlease report any issues.\n\n[\"plugin\" on pkg.go.dev](https://pkg.go.dev/plugin)", + "synopsis": "Package plugin implements loading and symbol resolution of Go plugins.\n\nA plugin is a Go main package with exported functions and variables that\nhas been built with:\n\n```\ngo build -buildmode=plugin\n\n```\nWhen a plugin is first opened, the init functions of all packages not\nalready part of the program are called. The main function is not run.\nA plugin is only initialized once, and cannot be closed.\n\n# Warnings\n\nThe ability to dynamically load parts of an application during\nexecution, perhaps based on user-defined configuration, may be a\nuseful building block in some designs. In particular, because\napplications and dynamically loaded functions can share data\nstructures directly, plugins may enable very high-performance\nintegration of separate parts.\n\nHowever, the plugin mechanism has many significant drawbacks that\nshould be considered carefully during the design. For example:\n\n - Plugins are currently supported only on Linux, FreeBSD, and\n macOS, making them unsuitable for applications intended to be\n portable.\n\n - Applications that use plugins may require careful configuration\n to ensure that the various parts of the program be made available\n in the correct location in the file system (or container image).\n By contrast, deploying an application consisting of a single static\n executable is straightforward.\n\n - Reasoning about program initialization is more difficult when\n some packages may not be initialized until long after the\n application has started running.\n\n - Bugs in applications that load plugins could be exploited by\n an attacker to load dangerous or untrusted libraries.\n\n - Runtime crashes are likely to occur unless all parts of the\n program (the application and all its plugins) are compiled\n using exactly the same version of the toolchain, the same build\n tags, and the same values of certain flags and environment\n variables.\n\n - Similar crashing problems are likely to arise unless all common\n dependencies of the application and its plugins are built from\n exactly the same source code.\n\n - Together, these restrictions mean that, in practice, the\n application and its plugins must all be built together by a\n single person or component of a system. In that case, it may\n be simpler for that person or component to generate Go source\n files that blank-import the desired set of plugins and then\n compile a static executable in the usual way.\n\nFor these reasons, many users decide that traditional interprocess\ncommunication (IPC) mechanisms such as sockets, pipes, remote\nprocedure call (RPC), shared memory mappings, or file system\noperations may be more suitable despite the performance overheads.\n\n[\"plugin\" on pkg.go.dev](https://pkg.go.dev/plugin)", "url": "https://pkg.go.dev/plugin", "path": "plugin", "children": [] @@ -950,13 +1030,13 @@ }, { "name": "regexp", - "synopsis": "Package regexp implements regular expression search.\n\nThe syntax of the regular expressions accepted is the same\ngeneral syntax used by Perl, Python, and other languages.\nMore precisely, it is the syntax accepted by RE2 and described at\nhttps://golang.org/s/re2syntax, except for \\C.\nFor an overview of the syntax, run\n go doc regexp/syntax\n\nThe regexp implementation provided by this package is\nguaranteed to run in time linear in the size of the input.\n(This is a property not guaranteed by most open source\nimplementations of regular expressions.) For more information\nabout this property, see\n```\nhttps://swtch.com/~rsc/regexp/regexp1.html\n```\nor any book about automata theory.\n\nAll characters are UTF-8-encoded code points.\nFollowing utf8.DecodeRune, each byte of an invalid UTF-8 sequence\nis treated as if it encoded utf8.RuneError (U+FFFD).\n\nThere are 16 methods of Regexp that match a regular expression and identify\nthe matched text. Their names are matched by this regular expression:\n\n```\nFind(All)?(String)?(Submatch)?(Index)?\n\n```\nIf 'All' is present, the routine matches successive non-overlapping\nmatches of the entire expression. Empty matches abutting a preceding\nmatch are ignored. The return value is a slice containing the successive\nreturn values of the corresponding non-'All' routine. These routines take\nan extra integer argument, n. If n \u003e= 0, the function returns at most n\nmatches/submatches; otherwise, it returns all of them.\n\nIf 'String' is present, the argument is a string; otherwise it is a slice\nof bytes; return values are adjusted as appropriate.\n\nIf 'Submatch' is present, the return value is a slice identifying the\nsuccessive submatches of the expression. Submatches are matches of\nparenthesized subexpressions (also known as capturing groups) within the\nregular expression, numbered from left to right in order of opening\nparenthesis. Submatch 0 is the match of the entire expression, submatch 1 is\nthe match of the first parenthesized subexpression, and so on.\n\nIf 'Index' is present, matches and submatches are identified by byte index\npairs within the input string: result[2*n:2*n+1] identifies the indexes of\nthe nth submatch. The pair for n==0 identifies the match of the entire\nexpression. If 'Index' is not present, the match is identified by the text\nof the match/submatch. If an index is negative or text is nil, it means that\nsubexpression did not match any string in the input. For 'String' versions\nan empty string means either no match or an empty match.\n\nThere is also a subset of the methods that can be applied to text read\nfrom a RuneReader:\n\n```\nMatchReader, FindReaderIndex, FindReaderSubmatchIndex\n\n```\nThis set may grow. Note that regular expression matches may need to\nexamine text beyond the text returned by a match, so the methods that\nmatch text from a RuneReader may read arbitrarily far into the input\nbefore returning.\n\n(There are a few other methods that do not match this pattern.)\n\n[\"regexp\" on pkg.go.dev](https://pkg.go.dev/regexp)", + "synopsis": "Package regexp implements regular expression search.\n\nThe syntax of the regular expressions accepted is the same\ngeneral syntax used by Perl, Python, and other languages.\nMore precisely, it is the syntax accepted by RE2 and described at\nhttps://golang.org/s/re2syntax, except for \\C.\nFor an overview of the syntax, run\n\n```\ngo doc regexp/syntax\n\n```\nThe regexp implementation provided by this package is\nguaranteed to run in time linear in the size of the input.\n(This is a property not guaranteed by most open source\nimplementations of regular expressions.) For more information\nabout this property, see\n\n```\nhttps://swtch.com/~rsc/regexp/regexp1.html\n\n```\nor any book about automata theory.\n\nAll characters are UTF-8-encoded code points.\nFollowing utf8.DecodeRune, each byte of an invalid UTF-8 sequence\nis treated as if it encoded utf8.RuneError (U+FFFD).\n\nThere are 16 methods of Regexp that match a regular expression and identify\nthe matched text. Their names are matched by this regular expression:\n\n```\nFind(All)?(String)?(Submatch)?(Index)?\n\n```\nIf 'All' is present, the routine matches successive non-overlapping\nmatches of the entire expression. Empty matches abutting a preceding\nmatch are ignored. The return value is a slice containing the successive\nreturn values of the corresponding non-'All' routine. These routines take\nan extra integer argument, n. If n \u003e= 0, the function returns at most n\nmatches/submatches; otherwise, it returns all of them.\n\nIf 'String' is present, the argument is a string; otherwise it is a slice\nof bytes; return values are adjusted as appropriate.\n\nIf 'Submatch' is present, the return value is a slice identifying the\nsuccessive submatches of the expression. Submatches are matches of\nparenthesized subexpressions (also known as capturing groups) within the\nregular expression, numbered from left to right in order of opening\nparenthesis. Submatch 0 is the match of the entire expression, submatch 1 is\nthe match of the first parenthesized subexpression, and so on.\n\nIf 'Index' is present, matches and submatches are identified by byte index\npairs within the input string: result[2*n:2*n+2] identifies the indexes of\nthe nth submatch. The pair for n==0 identifies the match of the entire\nexpression. If 'Index' is not present, the match is identified by the text\nof the match/submatch. If an index is negative or text is nil, it means that\nsubexpression did not match any string in the input. For 'String' versions\nan empty string means either no match or an empty match.\n\nThere is also a subset of the methods that can be applied to text read\nfrom a RuneReader:\n\n```\nMatchReader, FindReaderIndex, FindReaderSubmatchIndex\n\n```\nThis set may grow. Note that regular expression matches may need to\nexamine text beyond the text returned by a match, so the methods that\nmatch text from a RuneReader may read arbitrarily far into the input\nbefore returning.\n\n(There are a few other methods that do not match this pattern.)\n\n[\"regexp\" on pkg.go.dev](https://pkg.go.dev/regexp)", "url": "https://pkg.go.dev/regexp", "path": "regexp", "children": [ { "name": "syntax", - "synopsis": "Package syntax parses regular expressions into parse trees and compiles\nparse trees into programs. Most clients of regular expressions will use the\nfacilities of package regexp (such as Compile and Match) instead of this package.\n\nSyntax\n\nThe regular expression syntax understood by this package when parsing with the Perl flag is as follows.\nParts of the syntax can be disabled by passing alternate flags to Parse.\n\nSingle characters:\n . any character, possibly including newline (flag s=true)\n [xyz] character class\n [^xyz] negated character class\n \\d Perl character class\n \\D negated Perl character class\n [[:alpha:]] ASCII character class\n [[:^alpha:]] negated ASCII character class\n \\pN Unicode character class (one-letter name)\n \\p{Greek} Unicode character class\n \\PN negated Unicode character class (one-letter name)\n \\P{Greek} negated Unicode character class\n\nComposites:\n xy x followed by y\n x|y x or y (prefer x)\n\nRepetitions:\n x* zero or more x, prefer more\n x+ one or more x, prefer more\n x? zero or one x, prefer one\n x{n,m} n or n+1 or ... or m x, prefer more\n x{n,} n or more x, prefer more\n x{n} exactly n x\n x*? zero or more x, prefer fewer\n x+? one or more x, prefer fewer\n x?? zero or one x, prefer zero\n x{n,m}? n or n+1 or ... or m x, prefer fewer\n x{n,}? n or more x, prefer fewer\n x{n}? exactly n x\n\nImplementation restriction: The counting forms x{n,m}, x{n,}, and x{n}\nreject forms that create a minimum or maximum repetition count above 1000.\nUnlimited repetitions are not subject to this restriction.\n\nGrouping:\n (re) numbered capturing group (submatch)\n (?P\u003cname\u003ere) named \u0026 numbered capturing group (submatch)\n (?:re) non-capturing group\n (?flags) set flags within current group; non-capturing\n (?flags:re) set flags during re; non-capturing\n\n Flag syntax is xyz (set) or -xyz (clear) or xy-z (set xy, clear z). The flags are:\n\n i case-insensitive (default false)\n m multi-line mode: ^ and $ match begin/end line in addition to begin/end text (default false)\n s let . match \\n (default false)\n U ungreedy: swap meaning of x* and x*?, x+ and x+?, etc (default false)\n\nEmpty strings:\n ^ at beginning of text or line (flag m=true)\n $ at end of text (like \\z not \\Z) or line (flag m=true)\n \\A at beginning of text\n \\b at ASCII word boundary (\\w on one side and \\W, \\A, or \\z on the other)\n \\B not at ASCII word boundary\n \\z at end of text\n\nEscape sequences:\n \\a bell (== \\007)\n \\f form feed (== \\014)\n \\t horizontal tab (== \\011)\n \\n newline (== \\012)\n \\r carriage return (== \\015)\n \\v vertical tab character (== \\013)\n \\* literal *, for any punctuation character *\n \\123 octal character code (up to three digits)\n \\x7F hex character code (exactly two digits)\n \\x{10FFFF} hex character code\n \\Q...\\E literal text ... even if ... has punctuation\n\nCharacter class elements:\n x single character\n A-Z character range (inclusive)\n \\d Perl character class\n [:foo:] ASCII character class foo\n \\p{Foo} Unicode character class Foo\n \\pF Unicode character class F (one-letter name)\n\nNamed character classes as character class elements:\n [\\d] digits (== \\d)\n [^\\d] not digits (== \\D)\n [\\D] not digits (== \\D)\n [^\\D] not not digits (== \\d)\n [[:name:]] named ASCII class inside character class (== [:name:])\n [^[:name:]] named ASCII class inside negated character class (== [:^name:])\n [\\p{Name}] named Unicode property inside character class (== \\p{Name})\n [^\\p{Name}] named Unicode property inside negated character class (== \\P{Name})\n\nPerl character classes (all ASCII-only):\n \\d digits (== [0-9])\n \\D not digits (== [^0-9])\n \\s whitespace (== [\\t\\n\\f\\r ])\n \\S not whitespace (== [^\\t\\n\\f\\r ])\n \\w word characters (== [0-9A-Za-z_])\n \\W not word characters (== [^0-9A-Za-z_])\n\nASCII character classes:\n [[:alnum:]] alphanumeric (== [0-9A-Za-z])\n [[:alpha:]] alphabetic (== [A-Za-z])\n [[:ascii:]] ASCII (== [\\x00-\\x7F])\n [[:blank:]] blank (== [\\t ])\n [[:cntrl:]] control (== [\\x00-\\x1F\\x7F])\n [[:digit:]] digits (== [0-9])\n [[:graph:]] graphical (== [!-~] == [A-Za-z0-9!\"#$%\u0026'()*+,\\-./:;\u003c=\u003e?@[\\\\\\]^_`{|}~])\n [[:lower:]] lower case (== [a-z])\n [[:print:]] printable (== [ -~] == [ [:graph:]])\n [[:punct:]] punctuation (== [!-/:-@[-`{-~])\n [[:space:]] whitespace (== [\\t\\n\\v\\f\\r ])\n [[:upper:]] upper case (== [A-Z])\n [[:word:]] word characters (== [0-9A-Za-z_])\n [[:xdigit:]] hex digit (== [0-9A-Fa-f])\n\nUnicode character classes are those in unicode.Categories and unicode.Scripts.\n\n[\"regexp/syntax\" on pkg.go.dev](https://pkg.go.dev/regexp/syntax)", + "synopsis": "Package syntax parses regular expressions into parse trees and compiles\nparse trees into programs. Most clients of regular expressions will use the\nfacilities of package regexp (such as Compile and Match) instead of this package.\n\n# Syntax\n\nThe regular expression syntax understood by this package when parsing with the Perl flag is as follows.\nParts of the syntax can be disabled by passing alternate flags to Parse.\n\nSingle characters:\n\n```\n. any character, possibly including newline (flag s=true)\n[xyz] character class\n[^xyz] negated character class\n\\d Perl character class\n\\D negated Perl character class\n[[:alpha:]] ASCII character class\n[[:^alpha:]] negated ASCII character class\n\\pN Unicode character class (one-letter name)\n\\p{Greek} Unicode character class\n\\PN negated Unicode character class (one-letter name)\n\\P{Greek} negated Unicode character class\n\n```\nComposites:\n\n```\nxy x followed by y\nx|y x or y (prefer x)\n\n```\nRepetitions:\n\n```\nx* zero or more x, prefer more\nx+ one or more x, prefer more\nx? zero or one x, prefer one\nx{n,m} n or n+1 or ... or m x, prefer more\nx{n,} n or more x, prefer more\nx{n} exactly n x\nx*? zero or more x, prefer fewer\nx+? one or more x, prefer fewer\nx?? zero or one x, prefer zero\nx{n,m}? n or n+1 or ... or m x, prefer fewer\nx{n,}? n or more x, prefer fewer\nx{n}? exactly n x\n\n```\nImplementation restriction: The counting forms x{n,m}, x{n,}, and x{n}\nreject forms that create a minimum or maximum repetition count above 1000.\nUnlimited repetitions are not subject to this restriction.\n\nGrouping:\n\n```\n(re) numbered capturing group (submatch)\n(?P\u003cname\u003ere) named \u0026 numbered capturing group (submatch)\n(?:re) non-capturing group\n(?flags) set flags within current group; non-capturing\n(?flags:re) set flags during re; non-capturing\n\nFlag syntax is xyz (set) or -xyz (clear) or xy-z (set xy, clear z). The flags are:\n\ni case-insensitive (default false)\nm multi-line mode: ^ and $ match begin/end line in addition to begin/end text (default false)\ns let . match \\n (default false)\nU ungreedy: swap meaning of x* and x*?, x+ and x+?, etc (default false)\n\n```\nEmpty strings:\n\n```\n^ at beginning of text or line (flag m=true)\n$ at end of text (like \\z not \\Z) or line (flag m=true)\n\\A at beginning of text\n\\b at ASCII word boundary (\\w on one side and \\W, \\A, or \\z on the other)\n\\B not at ASCII word boundary\n\\z at end of text\n\n```\nEscape sequences:\n\n```\n\\a bell (== \\007)\n\\f form feed (== \\014)\n\\t horizontal tab (== \\011)\n\\n newline (== \\012)\n\\r carriage return (== \\015)\n\\v vertical tab character (== \\013)\n\\* literal *, for any punctuation character *\n\\123 octal character code (up to three digits)\n\\x7F hex character code (exactly two digits)\n\\x{10FFFF} hex character code\n\\Q...\\E literal text ... even if ... has punctuation\n\n```\nCharacter class elements:\n\n```\nx single character\nA-Z character range (inclusive)\n\\d Perl character class\n[:foo:] ASCII character class foo\n\\p{Foo} Unicode character class Foo\n\\pF Unicode character class F (one-letter name)\n\n```\nNamed character classes as character class elements:\n\n```\n[\\d] digits (== \\d)\n[^\\d] not digits (== \\D)\n[\\D] not digits (== \\D)\n[^\\D] not not digits (== \\d)\n[[:name:]] named ASCII class inside character class (== [:name:])\n[^[:name:]] named ASCII class inside negated character class (== [:^name:])\n[\\p{Name}] named Unicode property inside character class (== \\p{Name})\n[^\\p{Name}] named Unicode property inside negated character class (== \\P{Name})\n\n```\nPerl character classes (all ASCII-only):\n\n```\n\\d digits (== [0-9])\n\\D not digits (== [^0-9])\n\\s whitespace (== [\\t\\n\\f\\r ])\n\\S not whitespace (== [^\\t\\n\\f\\r ])\n\\w word characters (== [0-9A-Za-z_])\n\\W not word characters (== [^0-9A-Za-z_])\n\n```\nASCII character classes:\n\n```\n[[:alnum:]] alphanumeric (== [0-9A-Za-z])\n[[:alpha:]] alphabetic (== [A-Za-z])\n[[:ascii:]] ASCII (== [\\x00-\\x7F])\n[[:blank:]] blank (== [\\t ])\n[[:cntrl:]] control (== [\\x00-\\x1F\\x7F])\n[[:digit:]] digits (== [0-9])\n[[:graph:]] graphical (== [!-~] == [A-Za-z0-9!\"#$%\u0026'()*+,\\-./:;\u003c=\u003e?@[\\\\\\]^_`{|}~])\n[[:lower:]] lower case (== [a-z])\n[[:print:]] printable (== [ -~] == [ [:graph:]])\n[[:punct:]] punctuation (== [!-/:-@[-`{-~])\n[[:space:]] whitespace (== [\\t\\n\\v\\f\\r ])\n[[:upper:]] upper case (== [A-Z])\n[[:word:]] word characters (== [0-9A-Za-z_])\n[[:xdigit:]] hex digit (== [0-9A-Fa-f])\n\n```\nUnicode character classes are those in unicode.Categories and unicode.Scripts.\n\n[\"regexp/syntax\" on pkg.go.dev](https://pkg.go.dev/regexp/syntax)", "url": "https://pkg.go.dev/regexp/syntax", "path": "regexp/syntax", "children": [] @@ -965,7 +1045,7 @@ }, { "name": "runtime", - "synopsis": "Package runtime contains operations that interact with Go's runtime system,\nsuch as functions to control goroutines. It also includes the low-level type information\nused by the reflect package; see reflect's documentation for the programmable\ninterface to the run-time type system.\n\nEnvironment Variables\n\nThe following environment variables ($name or %name%, depending on the host\noperating system) control the run-time behavior of Go programs. The meanings\nand use may change from release to release.\n\nThe GOGC variable sets the initial garbage collection target percentage.\nA collection is triggered when the ratio of freshly allocated data to live data\nremaining after the previous collection reaches this percentage. The default\nis GOGC=100. Setting GOGC=off disables the garbage collector entirely.\nThe runtime/debug package's SetGCPercent function allows changing this\npercentage at run time. See https://golang.org/pkg/runtime/debug/#SetGCPercent.\n\nThe GODEBUG variable controls debugging variables within the runtime.\nIt is a comma-separated list of name=val pairs setting these named variables:\n\n```\nallocfreetrace: setting allocfreetrace=1 causes every allocation to be\nprofiled and a stack trace printed on each object's allocation and free.\n\nclobberfree: setting clobberfree=1 causes the garbage collector to\nclobber the memory content of an object with bad content when it frees\nthe object.\n\ncgocheck: setting cgocheck=0 disables all checks for packages\nusing cgo to incorrectly pass Go pointers to non-Go code.\nSetting cgocheck=1 (the default) enables relatively cheap\nchecks that may miss some errors. Setting cgocheck=2 enables\nexpensive checks that should not miss any errors, but will\ncause your program to run slower.\n\nefence: setting efence=1 causes the allocator to run in a mode\nwhere each object is allocated on a unique page and addresses are\nnever recycled.\n\ngccheckmark: setting gccheckmark=1 enables verification of the\ngarbage collector's concurrent mark phase by performing a\nsecond mark pass while the world is stopped. If the second\npass finds a reachable object that was not found by concurrent\nmark, the garbage collector will panic.\n\ngcpacertrace: setting gcpacertrace=1 causes the garbage collector to\nprint information about the internal state of the concurrent pacer.\n\ngcshrinkstackoff: setting gcshrinkstackoff=1 disables moving goroutines\nonto smaller stacks. In this mode, a goroutine's stack can only grow.\n\ngcstoptheworld: setting gcstoptheworld=1 disables concurrent garbage collection,\nmaking every garbage collection a stop-the-world event. Setting gcstoptheworld=2\nalso disables concurrent sweeping after the garbage collection finishes.\n\ngctrace: setting gctrace=1 causes the garbage collector to emit a single line to standard\nerror at each collection, summarizing the amount of memory collected and the\nlength of the pause. The format of this line is subject to change.\nCurrently, it is:\n\tgc # @#s #%: #+#+# ms clock, #+#/#/#+# ms cpu, #-\u003e#-\u003e# MB, # MB goal, # P\nwhere the fields are as follows:\n\tgc # the GC number, incremented at each GC\n\t@#s time in seconds since program start\n\t#% percentage of time spent in GC since program start\n\t#+...+# wall-clock/CPU times for the phases of the GC\n\t#-\u003e#-\u003e# MB heap size at GC start, at GC end, and live heap\n\t# MB goal goal heap size\n\t# P number of processors used\nThe phases are stop-the-world (STW) sweep termination, concurrent\nmark and scan, and STW mark termination. The CPU times\nfor mark/scan are broken down in to assist time (GC performed in\nline with allocation), background GC time, and idle GC time.\nIf the line ends with \"(forced)\", this GC was forced by a\nruntime.GC() call.\n\nharddecommit: setting harddecommit=1 causes memory that is returned to the OS to\nalso have protections removed on it. This is the only mode of operation on Windows,\nbut is helpful in debugging scavenger-related issues on other platforms. Currently,\nonly supported on Linux.\n\ninittrace: setting inittrace=1 causes the runtime to emit a single line to standard\nerror for each package with init work, summarizing the execution time and memory\nallocation. No information is printed for inits executed as part of plugin loading\nand for packages without both user defined and compiler generated init work.\nThe format of this line is subject to change. Currently, it is:\n\tinit # @#ms, # ms clock, # bytes, # allocs\nwhere the fields are as follows:\n\tinit # the package name\n\t@# ms time in milliseconds when the init started since program start\n\t# clock wall-clock time for package initialization work\n\t# bytes memory allocated on the heap\n\t# allocs number of heap allocations\n\nmadvdontneed: setting madvdontneed=0 will use MADV_FREE\ninstead of MADV_DONTNEED on Linux when returning memory to the\nkernel. This is more efficient, but means RSS numbers will\ndrop only when the OS is under memory pressure.\n\nmemprofilerate: setting memprofilerate=X will update the value of runtime.MemProfileRate.\nWhen set to 0 memory profiling is disabled. Refer to the description of\nMemProfileRate for the default value.\n\ninvalidptr: invalidptr=1 (the default) causes the garbage collector and stack\ncopier to crash the program if an invalid pointer value (for example, 1)\nis found in a pointer-typed location. Setting invalidptr=0 disables this check.\nThis should only be used as a temporary workaround to diagnose buggy code.\nThe real fix is to not store integers in pointer-typed locations.\n\nsbrk: setting sbrk=1 replaces the memory allocator and garbage collector\nwith a trivial allocator that obtains memory from the operating system and\nnever reclaims any memory.\n\nscavtrace: setting scavtrace=1 causes the runtime to emit a single line to standard\nerror, roughly once per GC cycle, summarizing the amount of work done by the\nscavenger as well as the total amount of memory returned to the operating system\nand an estimate of physical memory utilization. The format of this line is subject\nto change, but currently it is:\n\tscav # # KiB work, # KiB total, #% util\nwhere the fields are as follows:\n\tscav # the scavenge cycle number\n\t# KiB work the amount of memory returned to the OS since the last line\n\t# KiB total the total amount of memory returned to the OS\n\t#% util the fraction of all unscavenged memory which is in-use\nIf the line ends with \"(forced)\", then scavenging was forced by a\ndebug.FreeOSMemory() call.\n\nscheddetail: setting schedtrace=X and scheddetail=1 causes the scheduler to emit\ndetailed multiline info every X milliseconds, describing state of the scheduler,\nprocessors, threads and goroutines.\n\nschedtrace: setting schedtrace=X causes the scheduler to emit a single line to standard\nerror every X milliseconds, summarizing the scheduler state.\n\ntracebackancestors: setting tracebackancestors=N extends tracebacks with the stacks at\nwhich goroutines were created, where N limits the number of ancestor goroutines to\nreport. This also extends the information returned by runtime.Stack. Ancestor's goroutine\nIDs will refer to the ID of the goroutine at the time of creation; it's possible for this\nID to be reused for another goroutine. Setting N to 0 will report no ancestry information.\n\nasyncpreemptoff: asyncpreemptoff=1 disables signal-based\nasynchronous goroutine preemption. This makes some loops\nnon-preemptible for long periods, which may delay GC and\ngoroutine scheduling. This is useful for debugging GC issues\nbecause it also disables the conservative stack scanning used\nfor asynchronously preempted goroutines.\n\n```\nThe net and net/http packages also refer to debugging variables in GODEBUG.\nSee the documentation for those packages for details.\n\nThe GOMAXPROCS variable limits the number of operating system threads that\ncan execute user-level Go code simultaneously. There is no limit to the number of threads\nthat can be blocked in system calls on behalf of Go code; those do not count against\nthe GOMAXPROCS limit. This package's GOMAXPROCS function queries and changes\nthe limit.\n\nThe GORACE variable configures the race detector, for programs built using -race.\nSee https://golang.org/doc/articles/race_detector.html for details.\n\nThe GOTRACEBACK variable controls the amount of output generated when a Go\nprogram fails due to an unrecovered panic or an unexpected runtime condition.\nBy default, a failure prints a stack trace for the current goroutine,\neliding functions internal to the run-time system, and then exits with exit code 2.\nThe failure prints stack traces for all goroutines if there is no current goroutine\nor the failure is internal to the run-time.\nGOTRACEBACK=none omits the goroutine stack traces entirely.\nGOTRACEBACK=single (the default) behaves as described above.\nGOTRACEBACK=all adds stack traces for all user-created goroutines.\nGOTRACEBACK=system is like ``all'' but adds stack frames for run-time functions\nand shows goroutines created internally by the run-time.\nGOTRACEBACK=crash is like ``system'' but crashes in an operating system-specific\nmanner instead of exiting. For example, on Unix systems, the crash raises\nSIGABRT to trigger a core dump.\nFor historical reasons, the GOTRACEBACK settings 0, 1, and 2 are synonyms for\nnone, all, and system, respectively.\nThe runtime/debug package's SetTraceback function allows increasing the\namount of output at run time, but it cannot reduce the amount below that\nspecified by the environment variable.\nSee https://golang.org/pkg/runtime/debug/#SetTraceback.\n\nThe GOARCH, GOOS, GOPATH, and GOROOT environment variables complete\nthe set of Go environment variables. They influence the building of Go programs\n(see https://golang.org/cmd/go and https://golang.org/pkg/go/build).\nGOARCH, GOOS, and GOROOT are recorded at compile time and made available by\nconstants or functions in this package, but they do not influence the execution\nof the run-time system.\n\n[\"runtime\" on pkg.go.dev](https://pkg.go.dev/runtime)", + "synopsis": "Package runtime contains operations that interact with Go's runtime system,\nsuch as functions to control goroutines. It also includes the low-level type information\nused by the reflect package; see reflect's documentation for the programmable\ninterface to the run-time type system.\n\n# Environment Variables\n\nThe following environment variables ($name or %name%, depending on the host\noperating system) control the run-time behavior of Go programs. The meanings\nand use may change from release to release.\n\nThe GOGC variable sets the initial garbage collection target percentage.\nA collection is triggered when the ratio of freshly allocated data to live data\nremaining after the previous collection reaches this percentage. The default\nis GOGC=100. Setting GOGC=off disables the garbage collector entirely.\n[runtime/debug.SetGCPercent] allows changing this percentage at run time.\n\nThe GOMEMLIMIT variable sets a soft memory limit for the runtime. This memory limit\nincludes the Go heap and all other memory managed by the runtime, and excludes\nexternal memory sources such as mappings of the binary itself, memory managed in\nother languages, and memory held by the operating system on behalf of the Go\nprogram. GOMEMLIMIT is a numeric value in bytes with an optional unit suffix.\nThe supported suffixes include B, KiB, MiB, GiB, and TiB. These suffixes\nrepresent quantities of bytes as defined by the IEC 80000-13 standard. That is,\nthey are based on powers of two: KiB means 2^10 bytes, MiB means 2^20 bytes,\nand so on. The default setting is math.MaxInt64, which effectively disables the\nmemory limit. [runtime/debug.SetMemoryLimit] allows changing this limit at run\ntime.\n\nThe GODEBUG variable controls debugging variables within the runtime.\nIt is a comma-separated list of name=val pairs setting these named variables:\n\n```\nallocfreetrace: setting allocfreetrace=1 causes every allocation to be\nprofiled and a stack trace printed on each object's allocation and free.\n\nclobberfree: setting clobberfree=1 causes the garbage collector to\nclobber the memory content of an object with bad content when it frees\nthe object.\n\ncpu.*: cpu.all=off disables the use of all optional instruction set extensions.\ncpu.extension=off disables use of instructions from the specified instruction set extension.\nextension is the lower case name for the instruction set extension such as sse41 or avx\nas listed in internal/cpu package. As an example cpu.avx=off disables runtime detection\nand thereby use of AVX instructions.\n\ncgocheck: setting cgocheck=0 disables all checks for packages\nusing cgo to incorrectly pass Go pointers to non-Go code.\nSetting cgocheck=1 (the default) enables relatively cheap\nchecks that may miss some errors. A more complete, but slow,\ncgocheck mode can be enabled using GOEXPERIMENT (which\nrequires a rebuild), see https://pkg.go.dev/internal/goexperiment for details.\n\ndontfreezetheworld: by default, the start of a fatal panic or throw\n\"freezes the world\", preempting all threads to stop all running\ngoroutines, which makes it possible to traceback all goroutines, and\nkeeps their state close to the point of panic. Setting\ndontfreezetheworld=1 disables this preemption, allowing goroutines to\ncontinue executing during panic processing. Note that goroutines that\nnaturally enter the scheduler will still stop. This can be useful when\ndebugging the runtime scheduler, as freezetheworld perturbs scheduler\nstate and thus may hide problems.\n\nefence: setting efence=1 causes the allocator to run in a mode\nwhere each object is allocated on a unique page and addresses are\nnever recycled.\n\ngccheckmark: setting gccheckmark=1 enables verification of the\ngarbage collector's concurrent mark phase by performing a\nsecond mark pass while the world is stopped. If the second\npass finds a reachable object that was not found by concurrent\nmark, the garbage collector will panic.\n\ngcpacertrace: setting gcpacertrace=1 causes the garbage collector to\nprint information about the internal state of the concurrent pacer.\n\ngcshrinkstackoff: setting gcshrinkstackoff=1 disables moving goroutines\nonto smaller stacks. In this mode, a goroutine's stack can only grow.\n\ngcstoptheworld: setting gcstoptheworld=1 disables concurrent garbage collection,\nmaking every garbage collection a stop-the-world event. Setting gcstoptheworld=2\nalso disables concurrent sweeping after the garbage collection finishes.\n\ngctrace: setting gctrace=1 causes the garbage collector to emit a single line to standard\nerror at each collection, summarizing the amount of memory collected and the\nlength of the pause. The format of this line is subject to change. Included in\nthe explanation below is also the relevant runtime/metrics metric for each field.\nCurrently, it is:\n\tgc # @#s #%: #+#+# ms clock, #+#/#/#+# ms cpu, #-\u003e#-\u003e# MB, # MB goal, # MB stacks, #MB globals, # P\nwhere the fields are as follows:\n\tgc # the GC number, incremented at each GC\n\t@#s time in seconds since program start\n\t#% percentage of time spent in GC since program start\n\t#+...+# wall-clock/CPU times for the phases of the GC\n\t#-\u003e#-\u003e# MB heap size at GC start, at GC end, and live heap, or /gc/scan/heap:bytes\n\t# MB goal goal heap size, or /gc/heap/goal:bytes\n\t# MB stacks estimated scannable stack size, or /gc/scan/stack:bytes\n\t# MB globals scannable global size, or /gc/scan/globals:bytes\n\t# P number of processors used, or /sched/gomaxprocs:threads\nThe phases are stop-the-world (STW) sweep termination, concurrent\nmark and scan, and STW mark termination. The CPU times\nfor mark/scan are broken down in to assist time (GC performed in\nline with allocation), background GC time, and idle GC time.\nIf the line ends with \"(forced)\", this GC was forced by a\nruntime.GC() call.\n\nharddecommit: setting harddecommit=1 causes memory that is returned to the OS to\nalso have protections removed on it. This is the only mode of operation on Windows,\nbut is helpful in debugging scavenger-related issues on other platforms. Currently,\nonly supported on Linux.\n\ninittrace: setting inittrace=1 causes the runtime to emit a single line to standard\nerror for each package with init work, summarizing the execution time and memory\nallocation. No information is printed for inits executed as part of plugin loading\nand for packages without both user defined and compiler generated init work.\nThe format of this line is subject to change. Currently, it is:\n\tinit # @#ms, # ms clock, # bytes, # allocs\nwhere the fields are as follows:\n\tinit # the package name\n\t@# ms time in milliseconds when the init started since program start\n\t# clock wall-clock time for package initialization work\n\t# bytes memory allocated on the heap\n\t# allocs number of heap allocations\n\nmadvdontneed: setting madvdontneed=0 will use MADV_FREE\ninstead of MADV_DONTNEED on Linux when returning memory to the\nkernel. This is more efficient, but means RSS numbers will\ndrop only when the OS is under memory pressure. On the BSDs and\nIllumos/Solaris, setting madvdontneed=1 will use MADV_DONTNEED instead\nof MADV_FREE. This is less efficient, but causes RSS numbers to drop\nmore quickly.\n\nmemprofilerate: setting memprofilerate=X will update the value of runtime.MemProfileRate.\nWhen set to 0 memory profiling is disabled. Refer to the description of\nMemProfileRate for the default value.\n\npagetrace: setting pagetrace=/path/to/file will write out a trace of page events\nthat can be viewed, analyzed, and visualized using the x/debug/cmd/pagetrace tool.\nBuild your program with GOEXPERIMENT=pagetrace to enable this functionality. Do not\nenable this functionality if your program is a setuid binary as it introduces a security\nrisk in that scenario. Currently not supported on Windows, plan9 or js/wasm. Setting this\noption for some applications can produce large traces, so use with care.\n\ninvalidptr: invalidptr=1 (the default) causes the garbage collector and stack\ncopier to crash the program if an invalid pointer value (for example, 1)\nis found in a pointer-typed location. Setting invalidptr=0 disables this check.\nThis should only be used as a temporary workaround to diagnose buggy code.\nThe real fix is to not store integers in pointer-typed locations.\n\nsbrk: setting sbrk=1 replaces the memory allocator and garbage collector\nwith a trivial allocator that obtains memory from the operating system and\nnever reclaims any memory.\n\nscavtrace: setting scavtrace=1 causes the runtime to emit a single line to standard\nerror, roughly once per GC cycle, summarizing the amount of work done by the\nscavenger as well as the total amount of memory returned to the operating system\nand an estimate of physical memory utilization. The format of this line is subject\nto change, but currently it is:\n\tscav # KiB work (bg), # KiB work (eager), # KiB total, #% util\nwhere the fields are as follows:\n\t# KiB work (bg) the amount of memory returned to the OS in the background since\n\t the last line\n\t# KiB work (eager) the amount of memory returned to the OS eagerly since the last line\n\t# KiB now the amount of address space currently returned to the OS\n\t#% util the fraction of all unscavenged heap memory which is in-use\nIf the line ends with \"(forced)\", then scavenging was forced by a\ndebug.FreeOSMemory() call.\n\nscheddetail: setting schedtrace=X and scheddetail=1 causes the scheduler to emit\ndetailed multiline info every X milliseconds, describing state of the scheduler,\nprocessors, threads and goroutines.\n\nschedtrace: setting schedtrace=X causes the scheduler to emit a single line to standard\nerror every X milliseconds, summarizing the scheduler state.\n\ntracebackancestors: setting tracebackancestors=N extends tracebacks with the stacks at\nwhich goroutines were created, where N limits the number of ancestor goroutines to\nreport. This also extends the information returned by runtime.Stack. Ancestor's goroutine\nIDs will refer to the ID of the goroutine at the time of creation; it's possible for this\nID to be reused for another goroutine. Setting N to 0 will report no ancestry information.\n\ntracefpunwindoff: setting tracefpunwindoff=1 forces the execution tracer to\nuse the runtime's default stack unwinder instead of frame pointer unwinding.\nThis increases tracer overhead, but could be helpful as a workaround or for\ndebugging unexpected regressions caused by frame pointer unwinding.\n\nasyncpreemptoff: asyncpreemptoff=1 disables signal-based\nasynchronous goroutine preemption. This makes some loops\nnon-preemptible for long periods, which may delay GC and\ngoroutine scheduling. This is useful for debugging GC issues\nbecause it also disables the conservative stack scanning used\nfor asynchronously preempted goroutines.\n\n```\nThe net and net/http packages also refer to debugging variables in GODEBUG.\nSee the documentation for those packages for details.\n\nThe GOMAXPROCS variable limits the number of operating system threads that\ncan execute user-level Go code simultaneously. There is no limit to the number of threads\nthat can be blocked in system calls on behalf of Go code; those do not count against\nthe GOMAXPROCS limit. This package's GOMAXPROCS function queries and changes\nthe limit.\n\nThe GORACE variable configures the race detector, for programs built using -race.\nSee https://golang.org/doc/articles/race_detector.html for details.\n\nThe GOTRACEBACK variable controls the amount of output generated when a Go\nprogram fails due to an unrecovered panic or an unexpected runtime condition.\nBy default, a failure prints a stack trace for the current goroutine,\neliding functions internal to the run-time system, and then exits with exit code 2.\nThe failure prints stack traces for all goroutines if there is no current goroutine\nor the failure is internal to the run-time.\nGOTRACEBACK=none omits the goroutine stack traces entirely.\nGOTRACEBACK=single (the default) behaves as described above.\nGOTRACEBACK=all adds stack traces for all user-created goroutines.\nGOTRACEBACK=system is like “all” but adds stack frames for run-time functions\nand shows goroutines created internally by the run-time.\nGOTRACEBACK=crash is like “system” but crashes in an operating system-specific\nmanner instead of exiting. For example, on Unix systems, the crash raises\nSIGABRT to trigger a core dump.\nGOTRACEBACK=wer is like “crash” but doesn't disable Windows Error Reporting (WER).\nFor historical reasons, the GOTRACEBACK settings 0, 1, and 2 are synonyms for\nnone, all, and system, respectively.\nThe runtime/debug package's SetTraceback function allows increasing the\namount of output at run time, but it cannot reduce the amount below that\nspecified by the environment variable.\nSee https://golang.org/pkg/runtime/debug/#SetTraceback.\n\nThe GOARCH, GOOS, GOPATH, and GOROOT environment variables complete\nthe set of Go environment variables. They influence the building of Go programs\n(see https://golang.org/cmd/go and https://golang.org/pkg/go/build).\nGOARCH, GOOS, and GOROOT are recorded at compile time and made available by\nconstants or functions in this package, but they do not influence the execution\nof the run-time system.\n\n# Security\n\nOn Unix platforms, Go's runtime system behaves slightly differently when a\nbinary is setuid/setgid or executed with setuid/setgid-like properties, in order\nto prevent dangerous behaviors. On Linux this is determined by checking for the\nAT_SECURE flag in the auxiliary vector, on the BSDs and Solaris/Illumos it is\ndetermined by checking the issetugid syscall, and on AIX it is determined by\nchecking if the uid/gid match the effective uid/gid.\n\nWhen the runtime determines the binary is setuid/setgid-like, it does three main\nthings:\n - The standard input/output file descriptors (0, 1, 2) are checked to be open.\n If any of them are closed, they are opened pointing at /dev/null.\n - The value of the GOTRACEBACK environment variable is set to 'none'.\n - When a signal is received that terminates the program, or the program\n encounters an unrecoverable panic that would otherwise override the value\n of GOTRACEBACK, the goroutine stack, registers, and other memory related\n information are omitted.\n\n[\"runtime\" on pkg.go.dev](https://pkg.go.dev/runtime)", "url": "https://pkg.go.dev/runtime", "path": "runtime", "children": [ @@ -983,6 +1063,13 @@ "path": "runtime/cgo", "children": [] }, + { + "name": "coverage", + "synopsis": "\n[\"runtime/coverage\" on pkg.go.dev](https://pkg.go.dev/runtime/coverage)", + "url": "https://pkg.go.dev/runtime/coverage", + "path": "runtime/coverage", + "children": [] + }, { "name": "debug", "synopsis": "Package debug contains facilities for programs to debug themselves while\nthey are running.\n\n[\"runtime/debug\" on pkg.go.dev](https://pkg.go.dev/runtime/debug)", @@ -992,7 +1079,7 @@ }, { "name": "metrics", - "synopsis": "Package metrics provides a stable interface to access implementation-defined\nmetrics exported by the Go runtime. This package is similar to existing functions\nlike runtime.ReadMemStats and debug.ReadGCStats, but significantly more general.\n\nThe set of metrics defined by this package may evolve as the runtime itself\nevolves, and also enables variation across Go implementations, whose relevant\nmetric sets may not intersect.\n\nInterface\n\nMetrics are designated by a string key, rather than, for example, a field name in\na struct. The full list of supported metrics is always available in the slice of\nDescriptions returned by All. Each Description also includes useful information\nabout the metric.\n\nThus, users of this API are encouraged to sample supported metrics defined by the\nslice returned by All to remain compatible across Go versions. Of course, situations\narise where reading specific metrics is critical. For these cases, users are\nencouraged to use build tags, and although metrics may be deprecated and removed,\nusers should consider this to be an exceptional and rare event, coinciding with a\nvery large change in a particular Go implementation.\n\nEach metric key also has a \"kind\" that describes the format of the metric's value.\nIn the interest of not breaking users of this package, the \"kind\" for a given metric\nis guaranteed not to change. If it must change, then a new metric will be introduced\nwith a new key and a new \"kind.\"\n\nMetric key format\n\nAs mentioned earlier, metric keys are strings. Their format is simple and well-defined,\ndesigned to be both human and machine readable. It is split into two components,\nseparated by a colon: a rooted path and a unit. The choice to include the unit in\nthe key is motivated by compatibility: if a metric's unit changes, its semantics likely\ndid also, and a new key should be introduced.\n\nFor more details on the precise definition of the metric key's path and unit formats, see\nthe documentation of the Name field of the Description struct.\n\nA note about floats\n\nThis package supports metrics whose values have a floating-point representation. In\norder to improve ease-of-use, this package promises to never produce the following\nclasses of floating-point values: NaN, infinity.\n\nSupported metrics\n\nBelow is the full list of supported metrics, ordered lexicographically.\n\n```\n/gc/cycles/automatic:gc-cycles\n\tCount of completed GC cycles generated by the Go runtime.\n\n/gc/cycles/forced:gc-cycles\n\tCount of completed GC cycles forced by the application.\n\n/gc/cycles/total:gc-cycles\n\tCount of all completed GC cycles.\n\n/gc/heap/allocs-by-size:bytes\n\tDistribution of heap allocations by approximate size.\n\tNote that this does not include tiny objects as defined by /gc/heap/tiny/allocs:objects,\n\tonly tiny blocks.\n\n/gc/heap/allocs:bytes\n\tCumulative sum of memory allocated to the heap by the application.\n\n/gc/heap/allocs:objects\n\tCumulative count of heap allocations triggered by the application.\n\tNote that this does not include tiny objects as defined by /gc/heap/tiny/allocs:objects,\n\tonly tiny blocks.\n\n/gc/heap/frees-by-size:bytes\n\tDistribution of freed heap allocations by approximate size.\n\tNote that this does not include tiny objects as defined by /gc/heap/tiny/allocs:objects,\n\tonly tiny blocks.\n\n/gc/heap/frees:bytes\n\tCumulative sum of heap memory freed by the garbage collector.\n\n/gc/heap/frees:objects\n\tCumulative count of heap allocations whose storage was freed by the garbage collector.\n\tNote that this does not include tiny objects as defined by /gc/heap/tiny/allocs:objects,\n\tonly tiny blocks.\n\n/gc/heap/goal:bytes\n\tHeap size target for the end of the GC cycle.\n\n/gc/heap/objects:objects\n\tNumber of objects, live or unswept, occupying heap memory.\n\n/gc/heap/tiny/allocs:objects\n\tCount of small allocations that are packed together into blocks.\n\tThese allocations are counted separately from other allocations\n\tbecause each individual allocation is not tracked by the runtime,\n\tonly their block. Each block is already accounted for in\n\tallocs-by-size and frees-by-size.\n\n/gc/pauses:seconds\n\tDistribution individual GC-related stop-the-world pause latencies.\n\n/memory/classes/heap/free:bytes\n\tMemory that is completely free and eligible to be returned to\n\tthe underlying system, but has not been. This metric is the\n\truntime's estimate of free address space that is backed by\n\tphysical memory.\n\n/memory/classes/heap/objects:bytes\n\tMemory occupied by live objects and dead objects that have\n\tnot yet been marked free by the garbage collector.\n\n/memory/classes/heap/released:bytes\n\tMemory that is completely free and has been returned to\n\tthe underlying system. This metric is the runtime's estimate of\n\tfree address space that is still mapped into the process, but\n\tis not backed by physical memory.\n\n/memory/classes/heap/stacks:bytes\n\tMemory allocated from the heap that is reserved for stack\n\tspace, whether or not it is currently in-use.\n\n/memory/classes/heap/unused:bytes\n\tMemory that is reserved for heap objects but is not currently\n\tused to hold heap objects.\n\n/memory/classes/metadata/mcache/free:bytes\n\tMemory that is reserved for runtime mcache structures, but\n\tnot in-use.\n\n/memory/classes/metadata/mcache/inuse:bytes\n\tMemory that is occupied by runtime mcache structures that\n\tare currently being used.\n\n/memory/classes/metadata/mspan/free:bytes\n\tMemory that is reserved for runtime mspan structures, but\n\tnot in-use.\n\n/memory/classes/metadata/mspan/inuse:bytes\n\tMemory that is occupied by runtime mspan structures that are\n\tcurrently being used.\n\n/memory/classes/metadata/other:bytes\n\tMemory that is reserved for or used to hold runtime\n\tmetadata.\n\n/memory/classes/os-stacks:bytes\n\tStack memory allocated by the underlying operating system.\n\n/memory/classes/other:bytes\n\tMemory used by execution trace buffers, structures for\n\tdebugging the runtime, finalizer and profiler specials, and\n\tmore.\n\n/memory/classes/profiling/buckets:bytes\n\tMemory that is used by the stack trace hash map used for\n\tprofiling.\n\n/memory/classes/total:bytes\n\tAll memory mapped by the Go runtime into the current process\n\tas read-write. Note that this does not include memory mapped\n\tby code called via cgo or via the syscall package.\n\tSum of all metrics in /memory/classes.\n\n/sched/goroutines:goroutines\n\tCount of live goroutines.\n\n/sched/latencies:seconds\n\tDistribution of the time goroutines have spent in the scheduler\n\tin a runnable state before actually running.\n\n[\"runtime/metrics\" on pkg.go.dev](https://pkg.go.dev/runtime/metrics)", + "synopsis": "Package metrics provides a stable interface to access implementation-defined\nmetrics exported by the Go runtime. This package is similar to existing functions\nlike [runtime.ReadMemStats] and [debug.ReadGCStats], but significantly more general.\n\nThe set of metrics defined by this package may evolve as the runtime itself\nevolves, and also enables variation across Go implementations, whose relevant\nmetric sets may not intersect.\n\n# Interface\n\nMetrics are designated by a string key, rather than, for example, a field name in\na struct. The full list of supported metrics is always available in the slice of\nDescriptions returned by All. Each Description also includes useful information\nabout the metric.\n\nThus, users of this API are encouraged to sample supported metrics defined by the\nslice returned by All to remain compatible across Go versions. Of course, situations\narise where reading specific metrics is critical. For these cases, users are\nencouraged to use build tags, and although metrics may be deprecated and removed,\nusers should consider this to be an exceptional and rare event, coinciding with a\nvery large change in a particular Go implementation.\n\nEach metric key also has a \"kind\" that describes the format of the metric's value.\nIn the interest of not breaking users of this package, the \"kind\" for a given metric\nis guaranteed not to change. If it must change, then a new metric will be introduced\nwith a new key and a new \"kind.\"\n\n# Metric key format\n\nAs mentioned earlier, metric keys are strings. Their format is simple and well-defined,\ndesigned to be both human and machine readable. It is split into two components,\nseparated by a colon: a rooted path and a unit. The choice to include the unit in\nthe key is motivated by compatibility: if a metric's unit changes, its semantics likely\ndid also, and a new key should be introduced.\n\nFor more details on the precise definition of the metric key's path and unit formats, see\nthe documentation of the Name field of the Description struct.\n\n# A note about floats\n\nThis package supports metrics whose values have a floating-point representation. In\norder to improve ease-of-use, this package promises to never produce the following\nclasses of floating-point values: NaN, infinity.\n\n# Supported metrics\n\nBelow is the full list of supported metrics, ordered lexicographically.\n\n```\n/cgo/go-to-c-calls:calls\n\tCount of calls made from Go to C by the current process.\n\n/cpu/classes/gc/mark/assist:cpu-seconds\n\tEstimated total CPU time goroutines spent performing GC\n\ttasks to assist the GC and prevent it from falling behind the\n\tapplication. This metric is an overestimate, and not directly\n\tcomparable to system CPU time measurements. Compare only with\n\tother /cpu/classes metrics.\n\n/cpu/classes/gc/mark/dedicated:cpu-seconds\n\tEstimated total CPU time spent performing GC tasks on processors\n\t(as defined by GOMAXPROCS) dedicated to those tasks. This metric\n\tis an overestimate, and not directly comparable to system CPU\n\ttime measurements. Compare only with other /cpu/classes metrics.\n\n/cpu/classes/gc/mark/idle:cpu-seconds\n\tEstimated total CPU time spent performing GC tasks on spare CPU\n\tresources that the Go scheduler could not otherwise find a use\n\tfor. This should be subtracted from the total GC CPU time to\n\tobtain a measure of compulsory GC CPU time. This metric is an\n\toverestimate, and not directly comparable to system CPU time\n\tmeasurements. Compare only with other /cpu/classes metrics.\n\n/cpu/classes/gc/pause:cpu-seconds\n\tEstimated total CPU time spent with the application paused by\n\tthe GC. Even if only one thread is running during the pause,\n\tthis is computed as GOMAXPROCS times the pause latency because\n\tnothing else can be executing. This is the exact sum of samples\n\tin /gc/pause:seconds if each sample is multiplied by GOMAXPROCS\n\tat the time it is taken. This metric is an overestimate,\n\tand not directly comparable to system CPU time measurements.\n\tCompare only with other /cpu/classes metrics.\n\n/cpu/classes/gc/total:cpu-seconds\n\tEstimated total CPU time spent performing GC tasks. This metric\n\tis an overestimate, and not directly comparable to system CPU\n\ttime measurements. Compare only with other /cpu/classes metrics.\n\tSum of all metrics in /cpu/classes/gc.\n\n/cpu/classes/idle:cpu-seconds\n\tEstimated total available CPU time not spent executing\n\tany Go or Go runtime code. In other words, the part of\n\t/cpu/classes/total:cpu-seconds that was unused. This metric is\n\tan overestimate, and not directly comparable to system CPU time\n\tmeasurements. Compare only with other /cpu/classes metrics.\n\n/cpu/classes/scavenge/assist:cpu-seconds\n\tEstimated total CPU time spent returning unused memory to the\n\tunderlying platform in response eagerly in response to memory\n\tpressure. This metric is an overestimate, and not directly\n\tcomparable to system CPU time measurements. Compare only with\n\tother /cpu/classes metrics.\n\n/cpu/classes/scavenge/background:cpu-seconds\n\tEstimated total CPU time spent performing background tasks to\n\treturn unused memory to the underlying platform. This metric is\n\tan overestimate, and not directly comparable to system CPU time\n\tmeasurements. Compare only with other /cpu/classes metrics.\n\n/cpu/classes/scavenge/total:cpu-seconds\n\tEstimated total CPU time spent performing tasks that return\n\tunused memory to the underlying platform. This metric is an\n\toverestimate, and not directly comparable to system CPU time\n\tmeasurements. Compare only with other /cpu/classes metrics.\n\tSum of all metrics in /cpu/classes/scavenge.\n\n/cpu/classes/total:cpu-seconds\n\tEstimated total available CPU time for user Go code or the Go\n\truntime, as defined by GOMAXPROCS. In other words, GOMAXPROCS\n\tintegrated over the wall-clock duration this process has been\n\texecuting for. This metric is an overestimate, and not directly\n\tcomparable to system CPU time measurements. Compare only with\n\tother /cpu/classes metrics. Sum of all metrics in /cpu/classes.\n\n/cpu/classes/user:cpu-seconds\n\tEstimated total CPU time spent running user Go code. This may\n\talso include some small amount of time spent in the Go runtime.\n\tThis metric is an overestimate, and not directly comparable\n\tto system CPU time measurements. Compare only with other\n\t/cpu/classes metrics.\n\n/gc/cycles/automatic:gc-cycles\n\tCount of completed GC cycles generated by the Go runtime.\n\n/gc/cycles/forced:gc-cycles\n\tCount of completed GC cycles forced by the application.\n\n/gc/cycles/total:gc-cycles\n\tCount of all completed GC cycles.\n\n/gc/gogc:percent\n\tHeap size target percentage configured by the user, otherwise\n\t100. This value is set by the GOGC environment variable, and the\n\truntime/debug.SetGCPercent function.\n\n/gc/gomemlimit:bytes\n\tGo runtime memory limit configured by the user, otherwise\n\tmath.MaxInt64. This value is set by the GOMEMLIMIT environment\n\tvariable, and the runtime/debug.SetMemoryLimit function.\n\n/gc/heap/allocs-by-size:bytes\n\tDistribution of heap allocations by approximate size.\n\tBucket counts increase monotonically. Note that this does not\n\tinclude tiny objects as defined by /gc/heap/tiny/allocs:objects,\n\tonly tiny blocks.\n\n/gc/heap/allocs:bytes\n\tCumulative sum of memory allocated to the heap by the\n\tapplication.\n\n/gc/heap/allocs:objects\n\tCumulative count of heap allocations triggered by the\n\tapplication. Note that this does not include tiny objects as\n\tdefined by /gc/heap/tiny/allocs:objects, only tiny blocks.\n\n/gc/heap/frees-by-size:bytes\n\tDistribution of freed heap allocations by approximate size.\n\tBucket counts increase monotonically. Note that this does not\n\tinclude tiny objects as defined by /gc/heap/tiny/allocs:objects,\n\tonly tiny blocks.\n\n/gc/heap/frees:bytes\n\tCumulative sum of heap memory freed by the garbage collector.\n\n/gc/heap/frees:objects\n\tCumulative count of heap allocations whose storage was freed\n\tby the garbage collector. Note that this does not include tiny\n\tobjects as defined by /gc/heap/tiny/allocs:objects, only tiny\n\tblocks.\n\n/gc/heap/goal:bytes\n\tHeap size target for the end of the GC cycle.\n\n/gc/heap/live:bytes\n\tHeap memory occupied by live objects that were marked by the\n\tprevious GC.\n\n/gc/heap/objects:objects\n\tNumber of objects, live or unswept, occupying heap memory.\n\n/gc/heap/tiny/allocs:objects\n\tCount of small allocations that are packed together into blocks.\n\tThese allocations are counted separately from other allocations\n\tbecause each individual allocation is not tracked by the\n\truntime, only their block. Each block is already accounted for\n\tin allocs-by-size and frees-by-size.\n\n/gc/limiter/last-enabled:gc-cycle\n\tGC cycle the last time the GC CPU limiter was enabled.\n\tThis metric is useful for diagnosing the root cause of an\n\tout-of-memory error, because the limiter trades memory for CPU\n\ttime when the GC's CPU time gets too high. This is most likely\n\tto occur with use of SetMemoryLimit. The first GC cycle is cycle\n\t1, so a value of 0 indicates that it was never enabled.\n\n/gc/pauses:seconds\n\tDistribution of individual GC-related stop-the-world pause\n\tlatencies. Bucket counts increase monotonically.\n\n/gc/scan/globals:bytes\n\tThe total amount of global variable space that is scannable.\n\n/gc/scan/heap:bytes\n\tThe total amount of heap space that is scannable.\n\n/gc/scan/stack:bytes\n\tThe number of bytes of stack that were scanned last GC cycle.\n\n/gc/scan/total:bytes\n\tThe total amount space that is scannable. Sum of all metrics in\n\t/gc/scan.\n\n/gc/stack/starting-size:bytes\n\tThe stack size of new goroutines.\n\n/godebug/non-default-behavior/execerrdot:events\n\tThe number of non-default behaviors executed by the os/exec\n\tpackage due to a non-default GODEBUG=execerrdot=... setting.\n\n/godebug/non-default-behavior/gocachehash:events\n\tThe number of non-default behaviors executed by the cmd/go\n\tpackage due to a non-default GODEBUG=gocachehash=... setting.\n\n/godebug/non-default-behavior/gocachetest:events\n\tThe number of non-default behaviors executed by the cmd/go\n\tpackage due to a non-default GODEBUG=gocachetest=... setting.\n\n/godebug/non-default-behavior/gocacheverify:events\n\tThe number of non-default behaviors executed by the cmd/go\n\tpackage due to a non-default GODEBUG=gocacheverify=... setting.\n\n/godebug/non-default-behavior/http2client:events\n\tThe number of non-default behaviors executed by the net/http\n\tpackage due to a non-default GODEBUG=http2client=... setting.\n\n/godebug/non-default-behavior/http2server:events\n\tThe number of non-default behaviors executed by the net/http\n\tpackage due to a non-default GODEBUG=http2server=... setting.\n\n/godebug/non-default-behavior/installgoroot:events\n\tThe number of non-default behaviors executed by the go/build\n\tpackage due to a non-default GODEBUG=installgoroot=... setting.\n\n/godebug/non-default-behavior/jstmpllitinterp:events\n\tThe number of non-default behaviors executed by\n\tthe html/template package due to a non-default\n\tGODEBUG=jstmpllitinterp=... setting.\n\n/godebug/non-default-behavior/multipartmaxheaders:events\n\tThe number of non-default behaviors executed by\n\tthe mime/multipart package due to a non-default\n\tGODEBUG=multipartmaxheaders=... setting.\n\n/godebug/non-default-behavior/multipartmaxparts:events\n\tThe number of non-default behaviors executed by\n\tthe mime/multipart package due to a non-default\n\tGODEBUG=multipartmaxparts=... setting.\n\n/godebug/non-default-behavior/multipathtcp:events\n\tThe number of non-default behaviors executed by the net package\n\tdue to a non-default GODEBUG=multipathtcp=... setting.\n\n/godebug/non-default-behavior/panicnil:events\n\tThe number of non-default behaviors executed by the runtime\n\tpackage due to a non-default GODEBUG=panicnil=... setting.\n\n/godebug/non-default-behavior/randautoseed:events\n\tThe number of non-default behaviors executed by the math/rand\n\tpackage due to a non-default GODEBUG=randautoseed=... setting.\n\n/godebug/non-default-behavior/tarinsecurepath:events\n\tThe number of non-default behaviors executed by the archive/tar\n\tpackage due to a non-default GODEBUG=tarinsecurepath=...\n\tsetting.\n\n/godebug/non-default-behavior/tlsmaxrsasize:events\n\tThe number of non-default behaviors executed by the crypto/tls\n\tpackage due to a non-default GODEBUG=tlsmaxrsasize=... setting.\n\n/godebug/non-default-behavior/x509sha1:events\n\tThe number of non-default behaviors executed by the crypto/x509\n\tpackage due to a non-default GODEBUG=x509sha1=... setting.\n\n/godebug/non-default-behavior/x509usefallbackroots:events\n\tThe number of non-default behaviors executed by the crypto/x509\n\tpackage due to a non-default GODEBUG=x509usefallbackroots=...\n\tsetting.\n\n/godebug/non-default-behavior/zipinsecurepath:events\n\tThe number of non-default behaviors executed by the archive/zip\n\tpackage due to a non-default GODEBUG=zipinsecurepath=...\n\tsetting.\n\n/memory/classes/heap/free:bytes\n\tMemory that is completely free and eligible to be returned to\n\tthe underlying system, but has not been. This metric is the\n\truntime's estimate of free address space that is backed by\n\tphysical memory.\n\n/memory/classes/heap/objects:bytes\n\tMemory occupied by live objects and dead objects that have not\n\tyet been marked free by the garbage collector.\n\n/memory/classes/heap/released:bytes\n\tMemory that is completely free and has been returned to the\n\tunderlying system. This metric is the runtime's estimate of free\n\taddress space that is still mapped into the process, but is not\n\tbacked by physical memory.\n\n/memory/classes/heap/stacks:bytes\n\tMemory allocated from the heap that is reserved for stack space,\n\twhether or not it is currently in-use. Currently, this\n\trepresents all stack memory for goroutines. It also includes all\n\tOS thread stacks in non-cgo programs. Note that stacks may be\n\tallocated differently in the future, and this may change.\n\n/memory/classes/heap/unused:bytes\n\tMemory that is reserved for heap objects but is not currently\n\tused to hold heap objects.\n\n/memory/classes/metadata/mcache/free:bytes\n\tMemory that is reserved for runtime mcache structures, but not\n\tin-use.\n\n/memory/classes/metadata/mcache/inuse:bytes\n\tMemory that is occupied by runtime mcache structures that are\n\tcurrently being used.\n\n/memory/classes/metadata/mspan/free:bytes\n\tMemory that is reserved for runtime mspan structures, but not\n\tin-use.\n\n/memory/classes/metadata/mspan/inuse:bytes\n\tMemory that is occupied by runtime mspan structures that are\n\tcurrently being used.\n\n/memory/classes/metadata/other:bytes\n\tMemory that is reserved for or used to hold runtime metadata.\n\n/memory/classes/os-stacks:bytes\n\tStack memory allocated by the underlying operating system.\n\tIn non-cgo programs this metric is currently zero. This may\n\tchange in the future.In cgo programs this metric includes\n\tOS thread stacks allocated directly from the OS. Currently,\n\tthis only accounts for one stack in c-shared and c-archive build\n\tmodes, and other sources of stacks from the OS are not measured.\n\tThis too may change in the future.\n\n/memory/classes/other:bytes\n\tMemory used by execution trace buffers, structures for debugging\n\tthe runtime, finalizer and profiler specials, and more.\n\n/memory/classes/profiling/buckets:bytes\n\tMemory that is used by the stack trace hash map used for\n\tprofiling.\n\n/memory/classes/total:bytes\n\tAll memory mapped by the Go runtime into the current process\n\tas read-write. Note that this does not include memory mapped\n\tby code called via cgo or via the syscall package. Sum of all\n\tmetrics in /memory/classes.\n\n/sched/gomaxprocs:threads\n\tThe current runtime.GOMAXPROCS setting, or the number of\n\toperating system threads that can execute user-level Go code\n\tsimultaneously.\n\n/sched/goroutines:goroutines\n\tCount of live goroutines.\n\n/sched/latencies:seconds\n\tDistribution of the time goroutines have spent in the scheduler\n\tin a runnable state before actually running. Bucket counts\n\tincrease monotonically.\n\n/sync/mutex/wait/total:seconds\n\tApproximate cumulative time goroutines have spent blocked\n\ton a sync.Mutex or sync.RWMutex. This metric is useful for\n\tidentifying global changes in lock contention. Collect a mutex\n\tor block profile using the runtime/pprof package for more\n\tdetailed contention data.\n\n[\"runtime/metrics\" on pkg.go.dev](https://pkg.go.dev/runtime/metrics)", "url": "https://pkg.go.dev/runtime/metrics", "path": "runtime/metrics", "children": [] @@ -1006,7 +1093,7 @@ }, { "name": "pprof", - "synopsis": "Package pprof writes runtime profiling data in the format expected\nby the pprof visualization tool.\n\nProfiling a Go program\n\nThe first step to profiling a Go program is to enable profiling.\nSupport for profiling benchmarks built with the standard testing\npackage is built into go test. For example, the following command\nruns benchmarks in the current directory and writes the CPU and\nmemory profiles to cpu.prof and mem.prof:\n\n go test -cpuprofile cpu.prof -memprofile mem.prof -bench .\n\nTo add equivalent profiling support to a standalone program, add\ncode like the following to your main function:\n\n var cpuprofile = flag.String(\"cpuprofile\", \"\", \"write cpu profile to `file`\")\n var memprofile = flag.String(\"memprofile\", \"\", \"write memory profile to `file`\")\n\n func main() {\n flag.Parse()\n if *cpuprofile != \"\" {\n f, err := os.Create(*cpuprofile)\n if err != nil {\n log.Fatal(\"could not create CPU profile: \", err)\n }\n defer f.Close() // error handling omitted for example\n if err := pprof.StartCPUProfile(f); err != nil {\n log.Fatal(\"could not start CPU profile: \", err)\n }\n defer pprof.StopCPUProfile()\n }\n\n // ... rest of the program ...\n\n if *memprofile != \"\" {\n f, err := os.Create(*memprofile)\n if err != nil {\n log.Fatal(\"could not create memory profile: \", err)\n }\n defer f.Close() // error handling omitted for example\n runtime.GC() // get up-to-date statistics\n if err := pprof.WriteHeapProfile(f); err != nil {\n log.Fatal(\"could not write memory profile: \", err)\n }\n }\n }\n\nThere is also a standard HTTP interface to profiling data. Adding\nthe following line will install handlers under the /debug/pprof/\nURL to download live profiles:\n\n import _ \"net/http/pprof\"\n\nSee the net/http/pprof package for more details.\n\nProfiles can then be visualized with the pprof tool:\n\n go tool pprof cpu.prof\n\nThere are many commands available from the pprof command line.\nCommonly used commands include \"top\", which prints a summary of the\ntop program hot-spots, and \"web\", which opens an interactive graph\nof hot-spots and their call graphs. Use \"help\" for information on\nall pprof commands.\n\nFor more information about pprof, see\nhttps://github.com/google/pprof/blob/master/doc/README.md.\n\n[\"runtime/pprof\" on pkg.go.dev](https://pkg.go.dev/runtime/pprof)", + "synopsis": "Package pprof writes runtime profiling data in the format expected\nby the pprof visualization tool.\n\n# Profiling a Go program\n\nThe first step to profiling a Go program is to enable profiling.\nSupport for profiling benchmarks built with the standard testing\npackage is built into go test. For example, the following command\nruns benchmarks in the current directory and writes the CPU and\nmemory profiles to cpu.prof and mem.prof:\n\n```\ngo test -cpuprofile cpu.prof -memprofile mem.prof -bench .\n\n```\nTo add equivalent profiling support to a standalone program, add\ncode like the following to your main function:\n\n```\nvar cpuprofile = flag.String(\"cpuprofile\", \"\", \"write cpu profile to `file`\")\nvar memprofile = flag.String(\"memprofile\", \"\", \"write memory profile to `file`\")\n\nfunc main() {\n flag.Parse()\n if *cpuprofile != \"\" {\n f, err := os.Create(*cpuprofile)\n if err != nil {\n log.Fatal(\"could not create CPU profile: \", err)\n }\n defer f.Close() // error handling omitted for example\n if err := pprof.StartCPUProfile(f); err != nil {\n log.Fatal(\"could not start CPU profile: \", err)\n }\n defer pprof.StopCPUProfile()\n }\n\n // ... rest of the program ...\n\n if *memprofile != \"\" {\n f, err := os.Create(*memprofile)\n if err != nil {\n log.Fatal(\"could not create memory profile: \", err)\n }\n defer f.Close() // error handling omitted for example\n runtime.GC() // get up-to-date statistics\n if err := pprof.WriteHeapProfile(f); err != nil {\n log.Fatal(\"could not write memory profile: \", err)\n }\n }\n}\n\n```\nThere is also a standard HTTP interface to profiling data. Adding\nthe following line will install handlers under the /debug/pprof/\nURL to download live profiles:\n\n```\nimport _ \"net/http/pprof\"\n\n```\nSee the net/http/pprof package for more details.\n\nProfiles can then be visualized with the pprof tool:\n\n```\ngo tool pprof cpu.prof\n\n```\nThere are many commands available from the pprof command line.\nCommonly used commands include \"top\", which prints a summary of the\ntop program hot-spots, and \"web\", which opens an interactive graph\nof hot-spots and their call graphs. Use \"help\" for information on\nall pprof commands.\n\nFor more information about pprof, see\nhttps://github.com/google/pprof/blob/master/doc/README.md.\n\n[\"runtime/pprof\" on pkg.go.dev](https://pkg.go.dev/runtime/pprof)", "url": "https://pkg.go.dev/runtime/pprof", "path": "runtime/pprof", "children": [] @@ -1020,13 +1107,20 @@ }, { "name": "trace", - "synopsis": "Package trace contains facilities for programs to generate traces\nfor the Go execution tracer.\n\nTracing runtime activities\n\nThe execution trace captures a wide range of execution events such as\ngoroutine creation/blocking/unblocking, syscall enter/exit/block,\nGC-related events, changes of heap size, processor start/stop, etc.\nA precise nanosecond-precision timestamp and a stack trace is\ncaptured for most events. The generated trace can be interpreted\nusing `go tool trace`.\n\nSupport for tracing tests and benchmarks built with the standard\ntesting package is built into `go test`. For example, the following\ncommand runs the test in the current directory and writes the trace\nfile (trace.out).\n\n go test -trace=trace.out\n\nThis runtime/trace package provides APIs to add equivalent tracing\nsupport to a standalone program. See the Example that demonstrates\nhow to use this API to enable tracing.\n\nThere is also a standard HTTP interface to trace data. Adding the\nfollowing line will install a handler under the /debug/pprof/trace URL\nto download a live trace:\n\n import _ \"net/http/pprof\"\n\nSee the net/http/pprof package for more details about all of the\ndebug endpoints installed by this import.\n\nUser annotation\n\nPackage trace provides user annotation APIs that can be used to\nlog interesting events during execution.\n\nThere are three types of user annotations: log messages, regions,\nand tasks.\n\nLog emits a timestamped message to the execution trace along with\nadditional information such as the category of the message and\nwhich goroutine called Log. The execution tracer provides UIs to filter\nand group goroutines using the log category and the message supplied\nin Log.\n\nA region is for logging a time interval during a goroutine's execution.\nBy definition, a region starts and ends in the same goroutine.\nRegions can be nested to represent subintervals.\nFor example, the following code records four regions in the execution\ntrace to trace the durations of sequential steps in a cappuccino making\noperation.\n\n trace.WithRegion(ctx, \"makeCappuccino\", func() {\n\n // orderID allows to identify a specific order\n // among many cappuccino order region records.\n trace.Log(ctx, \"orderID\", orderID)\n\n trace.WithRegion(ctx, \"steamMilk\", steamMilk)\n trace.WithRegion(ctx, \"extractCoffee\", extractCoffee)\n trace.WithRegion(ctx, \"mixMilkCoffee\", mixMilkCoffee)\n })\n\nA task is a higher-level component that aids tracing of logical\noperations such as an RPC request, an HTTP request, or an\ninteresting local operation which may require multiple goroutines\nworking together. Since tasks can involve multiple goroutines,\nthey are tracked via a context.Context object. NewTask creates\na new task and embeds it in the returned context.Context object.\nLog messages and regions are attached to the task, if any, in the\nContext passed to Log and WithRegion.\n\nFor example, assume that we decided to froth milk, extract coffee,\nand mix milk and coffee in separate goroutines. With a task,\nthe trace tool can identify the goroutines involved in a specific\ncappuccino order.\n\n ctx, task := trace.NewTask(ctx, \"makeCappuccino\")\n trace.Log(ctx, \"orderID\", orderID)\n\n milk := make(chan bool)\n espresso := make(chan bool)\n\n go func() {\n trace.WithRegion(ctx, \"steamMilk\", steamMilk)\n milk \u003c- true\n }()\n go func() {\n trace.WithRegion(ctx, \"extractCoffee\", extractCoffee)\n espresso \u003c- true\n }()\n go func() {\n defer task.End() // When assemble is done, the order is complete.\n \u003c-espresso\n \u003c-milk\n trace.WithRegion(ctx, \"mixMilkCoffee\", mixMilkCoffee)\n }()\n\nThe trace tool computes the latency of a task by measuring the\ntime between the task creation and the task end and provides\nlatency distributions for each task type found in the trace.\n\n[\"runtime/trace\" on pkg.go.dev](https://pkg.go.dev/runtime/trace)", + "synopsis": "Package trace contains facilities for programs to generate traces\nfor the Go execution tracer.\n\n# Tracing runtime activities\n\nThe execution trace captures a wide range of execution events such as\ngoroutine creation/blocking/unblocking, syscall enter/exit/block,\nGC-related events, changes of heap size, processor start/stop, etc.\nWhen CPU profiling is active, the execution tracer makes an effort to\ninclude those samples as well.\nA precise nanosecond-precision timestamp and a stack trace is\ncaptured for most events. The generated trace can be interpreted\nusing `go tool trace`.\n\nSupport for tracing tests and benchmarks built with the standard\ntesting package is built into `go test`. For example, the following\ncommand runs the test in the current directory and writes the trace\nfile (trace.out).\n\n```\ngo test -trace=trace.out\n\n```\nThis runtime/trace package provides APIs to add equivalent tracing\nsupport to a standalone program. See the Example that demonstrates\nhow to use this API to enable tracing.\n\nThere is also a standard HTTP interface to trace data. Adding the\nfollowing line will install a handler under the /debug/pprof/trace URL\nto download a live trace:\n\n```\nimport _ \"net/http/pprof\"\n\n```\nSee the [net/http/pprof] package for more details about all of the\ndebug endpoints installed by this import.\n\n# User annotation\n\nPackage trace provides user annotation APIs that can be used to\nlog interesting events during execution.\n\nThere are three types of user annotations: log messages, regions,\nand tasks.\n\n[Log] emits a timestamped message to the execution trace along with\nadditional information such as the category of the message and\nwhich goroutine called [Log]. The execution tracer provides UIs to filter\nand group goroutines using the log category and the message supplied\nin [Log].\n\nA region is for logging a time interval during a goroutine's execution.\nBy definition, a region starts and ends in the same goroutine.\nRegions can be nested to represent subintervals.\nFor example, the following code records four regions in the execution\ntrace to trace the durations of sequential steps in a cappuccino making\noperation.\n\n```\ntrace.WithRegion(ctx, \"makeCappuccino\", func() {\n\n // orderID allows to identify a specific order\n // among many cappuccino order region records.\n trace.Log(ctx, \"orderID\", orderID)\n\n trace.WithRegion(ctx, \"steamMilk\", steamMilk)\n trace.WithRegion(ctx, \"extractCoffee\", extractCoffee)\n trace.WithRegion(ctx, \"mixMilkCoffee\", mixMilkCoffee)\n})\n\n```\nA task is a higher-level component that aids tracing of logical\noperations such as an RPC request, an HTTP request, or an\ninteresting local operation which may require multiple goroutines\nworking together. Since tasks can involve multiple goroutines,\nthey are tracked via a [context.Context] object. [NewTask] creates\na new task and embeds it in the returned [context.Context] object.\nLog messages and regions are attached to the task, if any, in the\nContext passed to [Log] and [WithRegion].\n\nFor example, assume that we decided to froth milk, extract coffee,\nand mix milk and coffee in separate goroutines. With a task,\nthe trace tool can identify the goroutines involved in a specific\ncappuccino order.\n\n```\nctx, task := trace.NewTask(ctx, \"makeCappuccino\")\ntrace.Log(ctx, \"orderID\", orderID)\n\nmilk := make(chan bool)\nespresso := make(chan bool)\n\ngo func() {\n trace.WithRegion(ctx, \"steamMilk\", steamMilk)\n milk \u003c- true\n}()\ngo func() {\n trace.WithRegion(ctx, \"extractCoffee\", extractCoffee)\n espresso \u003c- true\n}()\ngo func() {\n defer task.End() // When assemble is done, the order is complete.\n \u003c-espresso\n \u003c-milk\n trace.WithRegion(ctx, \"mixMilkCoffee\", mixMilkCoffee)\n}()\n\n```\nThe trace tool computes the latency of a task by measuring the\ntime between the task creation and the task end and provides\nlatency distributions for each task type found in the trace.\n\n[\"runtime/trace\" on pkg.go.dev](https://pkg.go.dev/runtime/trace)", "url": "https://pkg.go.dev/runtime/trace", "path": "runtime/trace", "children": [] } ] }, + { + "name": "slices", + "synopsis": "Package slices defines various functions useful with slices of any type.\n\n[\"slices\" on pkg.go.dev](https://pkg.go.dev/slices)", + "url": "https://pkg.go.dev/slices", + "path": "slices", + "children": [] + }, { "name": "sort", "synopsis": "Package sort provides primitives for sorting slices and user-defined collections.\n\n[\"sort\" on pkg.go.dev](https://pkg.go.dev/sort)", @@ -1036,7 +1130,7 @@ }, { "name": "strconv", - "synopsis": "Package strconv implements conversions to and from string representations\nof basic data types.\n\nNumeric Conversions\n\nThe most common numeric conversions are Atoi (string to int) and Itoa (int to string).\n\n```\ni, err := strconv.Atoi(\"-42\")\ns := strconv.Itoa(-42)\n\n```\nThese assume decimal and the Go int type.\n\nParseBool, ParseFloat, ParseInt, and ParseUint convert strings to values:\n\n```\nb, err := strconv.ParseBool(\"true\")\nf, err := strconv.ParseFloat(\"3.1415\", 64)\ni, err := strconv.ParseInt(\"-42\", 10, 64)\nu, err := strconv.ParseUint(\"42\", 10, 64)\n\n```\nThe parse functions return the widest type (float64, int64, and uint64),\nbut if the size argument specifies a narrower width the result can be\nconverted to that narrower type without data loss:\n\n```\ns := \"2147483647\" // biggest int32\ni64, err := strconv.ParseInt(s, 10, 32)\n...\ni := int32(i64)\n\n```\nFormatBool, FormatFloat, FormatInt, and FormatUint convert values to strings:\n\n```\ns := strconv.FormatBool(true)\ns := strconv.FormatFloat(3.1415, 'E', -1, 64)\ns := strconv.FormatInt(-42, 16)\ns := strconv.FormatUint(42, 16)\n\n```\nAppendBool, AppendFloat, AppendInt, and AppendUint are similar but\nappend the formatted value to a destination slice.\n\nString Conversions\n\nQuote and QuoteToASCII convert strings to quoted Go string literals.\nThe latter guarantees that the result is an ASCII string, by escaping\nany non-ASCII Unicode with \\u:\n\n```\nq := strconv.Quote(\"Hello, 世界\")\nq := strconv.QuoteToASCII(\"Hello, 世界\")\n\n```\nQuoteRune and QuoteRuneToASCII are similar but accept runes and\nreturn quoted Go rune literals.\n\nUnquote and UnquoteChar unquote Go string and rune literals.\n\n[\"strconv\" on pkg.go.dev](https://pkg.go.dev/strconv)", + "synopsis": "Package strconv implements conversions to and from string representations\nof basic data types.\n\n# Numeric Conversions\n\nThe most common numeric conversions are Atoi (string to int) and Itoa (int to string).\n\n```\ni, err := strconv.Atoi(\"-42\")\ns := strconv.Itoa(-42)\n\n```\nThese assume decimal and the Go int type.\n\n[ParseBool], [ParseFloat], [ParseInt], and [ParseUint] convert strings to values:\n\n```\nb, err := strconv.ParseBool(\"true\")\nf, err := strconv.ParseFloat(\"3.1415\", 64)\ni, err := strconv.ParseInt(\"-42\", 10, 64)\nu, err := strconv.ParseUint(\"42\", 10, 64)\n\n```\nThe parse functions return the widest type (float64, int64, and uint64),\nbut if the size argument specifies a narrower width the result can be\nconverted to that narrower type without data loss:\n\n```\ns := \"2147483647\" // biggest int32\ni64, err := strconv.ParseInt(s, 10, 32)\n...\ni := int32(i64)\n\n```\n[FormatBool], [FormatFloat], [FormatInt], and [FormatUint] convert values to strings:\n\n```\ns := strconv.FormatBool(true)\ns := strconv.FormatFloat(3.1415, 'E', -1, 64)\ns := strconv.FormatInt(-42, 16)\ns := strconv.FormatUint(42, 16)\n\n```\n[AppendBool], [AppendFloat], [AppendInt], and [AppendUint] are similar but\nappend the formatted value to a destination slice.\n\n# String Conversions\n\n[Quote] and [QuoteToASCII] convert strings to quoted Go string literals.\nThe latter guarantees that the result is an ASCII string, by escaping\nany non-ASCII Unicode with \\u:\n\n```\nq := strconv.Quote(\"Hello, 世界\")\nq := strconv.QuoteToASCII(\"Hello, 世界\")\n\n```\n[QuoteRune] and [QuoteRuneToASCII] are similar but accept runes and\nreturn quoted Go rune literals.\n\n[Unquote] and [UnquoteChar] unquote Go string and rune literals.\n\n[\"strconv\" on pkg.go.dev](https://pkg.go.dev/strconv)", "url": "https://pkg.go.dev/strconv", "path": "strconv", "children": [] @@ -1056,7 +1150,7 @@ "children": [ { "name": "atomic", - "synopsis": "Package atomic provides low-level atomic memory primitives\nuseful for implementing synchronization algorithms.\n\nThese functions require great care to be used correctly.\nExcept for special, low-level applications, synchronization is better\ndone with channels or the facilities of the sync package.\nShare memory by communicating;\ndon't communicate by sharing memory.\n\nThe swap operation, implemented by the SwapT functions, is the atomic\nequivalent of:\n\n```\nold = *addr\n*addr = new\nreturn old\n\n```\nThe compare-and-swap operation, implemented by the CompareAndSwapT\nfunctions, is the atomic equivalent of:\n\n```\nif *addr == old {\n\t*addr = new\n\treturn true\n}\nreturn false\n\n```\nThe add operation, implemented by the AddT functions, is the atomic\nequivalent of:\n\n```\n*addr += delta\nreturn *addr\n\n```\nThe load and store operations, implemented by the LoadT and StoreT\nfunctions, are the atomic equivalents of \"return *addr\" and\n\"*addr = val\".\n\n[\"sync/atomic\" on pkg.go.dev](https://pkg.go.dev/sync/atomic)", + "synopsis": "Package atomic provides low-level atomic memory primitives\nuseful for implementing synchronization algorithms.\n\nThese functions require great care to be used correctly.\nExcept for special, low-level applications, synchronization is better\ndone with channels or the facilities of the [sync] package.\nShare memory by communicating;\ndon't communicate by sharing memory.\n\nThe swap operation, implemented by the SwapT functions, is the atomic\nequivalent of:\n\n```\nold = *addr\n*addr = new\nreturn old\n\n```\nThe compare-and-swap operation, implemented by the CompareAndSwapT\nfunctions, is the atomic equivalent of:\n\n```\nif *addr == old {\n\t*addr = new\n\treturn true\n}\nreturn false\n\n```\nThe add operation, implemented by the AddT functions, is the atomic\nequivalent of:\n\n```\n*addr += delta\nreturn *addr\n\n```\nThe load and store operations, implemented by the LoadT and StoreT\nfunctions, are the atomic equivalents of \"return *addr\" and\n\"*addr = val\".\n\nIn the terminology of the Go memory model, if the effect of\nan atomic operation A is observed by atomic operation B,\nthen A “synchronizes before” B.\nAdditionally, all the atomic operations executed in a program\nbehave as though executed in some sequentially consistent order.\nThis definition provides the same semantics as\nC++'s sequentially consistent atomics and Java's volatile variables.\n\n[\"sync/atomic\" on pkg.go.dev](https://pkg.go.dev/sync/atomic)", "url": "https://pkg.go.dev/sync/atomic", "path": "sync/atomic", "children": [] @@ -1080,7 +1174,7 @@ }, { "name": "testing", - "synopsis": "Package testing provides support for automated testing of Go packages.\nIt is intended to be used in concert with the \"go test\" command, which automates\nexecution of any function of the form\n func TestXxx(*testing.T)\nwhere Xxx does not start with a lowercase letter. The function name\nserves to identify the test routine.\n\nWithin these functions, use the Error, Fail or related methods to signal failure.\n\nTo write a new test suite, create a file whose name ends _test.go that\ncontains the TestXxx functions as described here. Put the file in the same\npackage as the one being tested. The file will be excluded from regular\npackage builds but will be included when the \"go test\" command is run.\nFor more detail, run \"go help test\" and \"go help testflag\".\n\nA simple test function looks like this:\n\n func TestAbs(t *testing.T) {\n got := Abs(-1)\n if got != 1 {\n t.Errorf(\"Abs(-1) = %d; want 1\", got)\n }\n }\n\nBenchmarks\n\nFunctions of the form\n func BenchmarkXxx(*testing.B)\nare considered benchmarks, and are executed by the \"go test\" command when\nits -bench flag is provided. Benchmarks are run sequentially.\n\nFor a description of the testing flags, see\nhttps://golang.org/cmd/go/#hdr-Testing_flags.\n\nA sample benchmark function looks like this:\n func BenchmarkRandInt(b *testing.B) {\n for i := 0; i \u003c b.N; i++ {\n rand.Int()\n }\n }\n\nThe benchmark function must run the target code b.N times.\nDuring benchmark execution, b.N is adjusted until the benchmark function lasts\nlong enough to be timed reliably. The output\n BenchmarkRandInt-8 \t68453040\t 17.8 ns/op\nmeans that the loop ran 68453040 times at a speed of 17.8 ns per loop.\n\nIf a benchmark needs some expensive setup before running, the timer\nmay be reset:\n\n func BenchmarkBigLen(b *testing.B) {\n big := NewBig()\n b.ResetTimer()\n for i := 0; i \u003c b.N; i++ {\n big.Len()\n }\n }\n\nIf a benchmark needs to test performance in a parallel setting, it may use\nthe RunParallel helper function; such benchmarks are intended to be used with\nthe go test -cpu flag:\n\n func BenchmarkTemplateParallel(b *testing.B) {\n templ := template.Must(template.New(\"test\").Parse(\"Hello, {{.}}!\"))\n b.RunParallel(func(pb *testing.PB) {\n var buf bytes.Buffer\n for pb.Next() {\n buf.Reset()\n templ.Execute(\u0026buf, \"World\")\n }\n })\n }\n\nA detailed specification of the benchmark results format is given\nin https://golang.org/design/14313-benchmark-format.\n\nThere are standard tools for working with benchmark results at\nhttps://golang.org/x/perf/cmd.\nIn particular, https://golang.org/x/perf/cmd/benchstat performs\nstatistically robust A/B comparisons.\n\nExamples\n\nThe package also runs and verifies example code. Example functions may\ninclude a concluding line comment that begins with \"Output:\" and is compared with\nthe standard output of the function when the tests are run. (The comparison\nignores leading and trailing space.) These are examples of an example:\n\n func ExampleHello() {\n fmt.Println(\"hello\")\n // Output: hello\n }\n\n func ExampleSalutations() {\n fmt.Println(\"hello, and\")\n fmt.Println(\"goodbye\")\n // Output:\n // hello, and\n // goodbye\n }\n\nThe comment prefix \"Unordered output:\" is like \"Output:\", but matches any\nline order:\n\n func ExamplePerm() {\n for _, value := range Perm(5) {\n fmt.Println(value)\n }\n // Unordered output: 4\n // 2\n // 1\n // 3\n // 0\n }\n\nExample functions without output comments are compiled but not executed.\n\nThe naming convention to declare examples for the package, a function F, a type T and\nmethod M on type T are:\n\n func Example() { ... }\n func ExampleF() { ... }\n func ExampleT() { ... }\n func ExampleT_M() { ... }\n\nMultiple example functions for a package/type/function/method may be provided by\nappending a distinct suffix to the name. The suffix must start with a\nlower-case letter.\n\n func Example_suffix() { ... }\n func ExampleF_suffix() { ... }\n func ExampleT_suffix() { ... }\n func ExampleT_M_suffix() { ... }\n\nThe entire test file is presented as the example when it contains a single\nexample function, at least one other function, type, variable, or constant\ndeclaration, and no test or benchmark functions.\n\nFuzzing\n\n'go test' and the testing package support fuzzing, a testing technique where\na function is called with randomly generated inputs to find bugs not\nanticipated by unit tests.\n\nFunctions of the form\n func FuzzXxx(*testing.F)\nare considered fuzz tests.\n\nFor example:\n\n func FuzzHex(f *testing.F) {\n for _, seed := range [][]byte{{}, {0}, {9}, {0xa}, {0xf}, {1, 2, 3, 4}} {\n f.Add(seed)\n }\n f.Fuzz(func(t *testing.T, in []byte) {\n enc := hex.EncodeToString(in)\n out, err := hex.DecodeString(enc)\n if err != nil {\n t.Fatalf(\"%v: decode: %v\", in, err)\n }\n if !bytes.Equal(in, out) {\n t.Fatalf(\"%v: not equal after round trip: %v\", in, out)\n }\n })\n }\n\nA fuzz test maintains a seed corpus, or a set of inputs which are run by\ndefault, and can seed input generation. Seed inputs may be registered by\ncalling (*F).Add or by storing files in the directory testdata/fuzz/\u003cName\u003e\n(where \u003cName\u003e is the name of the fuzz test) within the package containing\nthe fuzz test. Seed inputs are optional, but the fuzzing engine may find\nbugs more efficiently when provided with a set of small seed inputs with good\ncode coverage. These seed inputs can also serve as regression tests for bugs\nidentified through fuzzing.\n\nThe function passed to (*F).Fuzz within the fuzz test is considered the fuzz\ntarget. A fuzz target must accept a *T parameter, followed by one or more\nparameters for random inputs. The types of arguments passed to (*F).Add must\nbe identical to the types of these parameters. The fuzz target may signal\nthat it's found a problem the same way tests do: by calling T.Fail (or any\nmethod that calls it like T.Error or T.Fatal) or by panicking.\n\nWhen fuzzing is enabled (by setting the -fuzz flag to a regular expression\nthat matches a specific fuzz test), the fuzz target is called with arguments\ngenerated by repeatedly making random changes to the seed inputs. On\nsupported platforms, 'go test' compiles the test executable with fuzzing\ncoverage instrumentation. The fuzzing engine uses that instrumentation to\nfind and cache inputs that expand coverage, increasing the likelihood of\nfinding bugs. If the fuzz target fails for a given input, the fuzzing engine\nwrites the inputs that caused the failure to a file in the directory\ntestdata/fuzz/\u003cName\u003e within the package directory. This file later serves as\na seed input. If the file can't be written at that location (for example,\nbecause the directory is read-only), the fuzzing engine writes the file to\nthe fuzz cache directory within the build cache instead.\n\nWhen fuzzing is disabled, the fuzz target is called with the seed inputs\nregistered with F.Add and seed inputs from testdata/fuzz/\u003cName\u003e. In this\nmode, the fuzz test acts much like a regular test, with subtests started\nwith F.Fuzz instead of T.Run.\n\nSee https://go.dev/doc/fuzz for documentation about fuzzing.\n\nSkipping\n\nTests or benchmarks may be skipped at run time with a call to\nthe Skip method of *T or *B:\n\n func TestTimeConsuming(t *testing.T) {\n if testing.Short() {\n t.Skip(\"skipping test in short mode.\")\n }\n ...\n }\n\nThe Skip method of *T can be used in a fuzz target if the input is invalid,\nbut should not be considered a failing input. For example:\n\n func FuzzJSONMarshalling(f *testing.F) {\n f.Fuzz(func(t *testing.T, b []byte) {\n var v interface{}\n if err := json.Unmarshal(b, \u0026v); err != nil {\n t.Skip()\n }\n if _, err := json.Marshal(v); err != nil {\n t.Error(\"Marshal: %v\", err)\n }\n })\n }\n\nSubtests and Sub-benchmarks\n\nThe Run methods of T and B allow defining subtests and sub-benchmarks,\nwithout having to define separate functions for each. This enables uses\nlike table-driven benchmarks and creating hierarchical tests.\nIt also provides a way to share common setup and tear-down code:\n\n func TestFoo(t *testing.T) {\n // \u003csetup code\u003e\n t.Run(\"A=1\", func(t *testing.T) { ... })\n t.Run(\"A=2\", func(t *testing.T) { ... })\n t.Run(\"B=1\", func(t *testing.T) { ... })\n // \u003ctear-down code\u003e\n }\n\nEach subtest and sub-benchmark has a unique name: the combination of the name\nof the top-level test and the sequence of names passed to Run, separated by\nslashes, with an optional trailing sequence number for disambiguation.\n\nThe argument to the -run, -bench, and -fuzz command-line flags is an unanchored regular\nexpression that matches the test's name. For tests with multiple slash-separated\nelements, such as subtests, the argument is itself slash-separated, with\nexpressions matching each name element in turn. Because it is unanchored, an\nempty expression matches any string.\nFor example, using \"matching\" to mean \"whose name contains\":\n\n go test -run '' # Run all tests.\n go test -run Foo # Run top-level tests matching \"Foo\", such as \"TestFooBar\".\n go test -run Foo/A= # For top-level tests matching \"Foo\", run subtests matching \"A=\".\n go test -run /A=1 # For all top-level tests, run subtests matching \"A=1\".\n go test -fuzz FuzzFoo # Fuzz the target matching \"FuzzFoo\"\n\nThe -run argument can also be used to run a specific value in the seed\ncorpus, for debugging. For example:\n go test -run=FuzzFoo/9ddb952d9814\n\nThe -fuzz and -run flags can both be set, in order to fuzz a target but\nskip the execution of all other tests.\n\nSubtests can also be used to control parallelism. A parent test will only\ncomplete once all of its subtests complete. In this example, all tests are\nrun in parallel with each other, and only with each other, regardless of\nother top-level tests that may be defined:\n\n func TestGroupedParallel(t *testing.T) {\n for _, tc := range tests {\n tc := tc // capture range variable\n t.Run(tc.Name, func(t *testing.T) {\n t.Parallel()\n ...\n })\n }\n }\n\nThe race detector kills the program if it exceeds 8128 concurrent goroutines,\nso use care when running parallel tests with the -race flag set.\n\nRun does not return until parallel subtests have completed, providing a way\nto clean up after a group of parallel tests:\n\n func TestTeardownParallel(t *testing.T) {\n // This Run will not return until the parallel tests finish.\n t.Run(\"group\", func(t *testing.T) {\n t.Run(\"Test1\", parallelTest1)\n t.Run(\"Test2\", parallelTest2)\n t.Run(\"Test3\", parallelTest3)\n })\n // \u003ctear-down code\u003e\n }\n\nMain\n\nIt is sometimes necessary for a test or benchmark program to do extra setup or teardown\nbefore or after it executes. It is also sometimes necessary to control\nwhich code runs on the main thread. To support these and other cases,\nif a test file contains a function:\n\n```\nfunc TestMain(m *testing.M)\n\n```\nthen the generated test will call TestMain(m) instead of running the tests or benchmarks\ndirectly. TestMain runs in the main goroutine and can do whatever setup\nand teardown is necessary around a call to m.Run. m.Run will return an exit\ncode that may be passed to os.Exit. If TestMain returns, the test wrapper\nwill pass the result of m.Run to os.Exit itself.\n\nWhen TestMain is called, flag.Parse has not been run. If TestMain depends on\ncommand-line flags, including those of the testing package, it should call\nflag.Parse explicitly. Command line flags are always parsed by the time test\nor benchmark functions run.\n\nA simple implementation of TestMain is:\n\n```\nfunc TestMain(m *testing.M) {\n\t// call flag.Parse() here if TestMain uses flags\n\tos.Exit(m.Run())\n}\n\n```\nTestMain is a low-level primitive and should not be necessary for casual\ntesting needs, where ordinary test functions suffice.\n\n[\"testing\" on pkg.go.dev](https://pkg.go.dev/testing)", + "synopsis": "Package testing provides support for automated testing of Go packages.\nIt is intended to be used in concert with the \"go test\" command, which automates\nexecution of any function of the form\n\n```\nfunc TestXxx(*testing.T)\n\n```\nwhere Xxx does not start with a lowercase letter. The function name\nserves to identify the test routine.\n\nWithin these functions, use the Error, Fail or related methods to signal failure.\n\nTo write a new test suite, create a file that\ncontains the TestXxx functions as described here,\nand give that file a name ending in \"_test.go\".\nThe file will be excluded from regular\npackage builds but will be included when the \"go test\" command is run.\n\nThe test file can be in the same package as the one being tested,\nor in a corresponding package with the suffix \"_test\".\n\nIf the test file is in the same package, it may refer to unexported\nidentifiers within the package, as in this example:\n\n```\npackage abs\n\nimport \"testing\"\n\nfunc TestAbs(t *testing.T) {\n got := Abs(-1)\n if got != 1 {\n t.Errorf(\"Abs(-1) = %d; want 1\", got)\n }\n}\n\n```\nIf the file is in a separate \"_test\" package, the package being tested\nmust be imported explicitly and only its exported identifiers may be used.\nThis is known as \"black box\" testing.\n\n```\npackage abs_test\n\nimport (\n\t\"testing\"\n\n\t\"path_to_pkg/abs\"\n)\n\nfunc TestAbs(t *testing.T) {\n got := abs.Abs(-1)\n if got != 1 {\n t.Errorf(\"Abs(-1) = %d; want 1\", got)\n }\n}\n\n```\nFor more detail, run \"go help test\" and \"go help testflag\".\n\n# Benchmarks\n\nFunctions of the form\n\n```\nfunc BenchmarkXxx(*testing.B)\n\n```\nare considered benchmarks, and are executed by the \"go test\" command when\nits -bench flag is provided. Benchmarks are run sequentially.\n\nFor a description of the testing flags, see\nhttps://golang.org/cmd/go/#hdr-Testing_flags.\n\nA sample benchmark function looks like this:\n\n```\nfunc BenchmarkRandInt(b *testing.B) {\n for i := 0; i \u003c b.N; i++ {\n rand.Int()\n }\n}\n\n```\nThe benchmark function must run the target code b.N times.\nDuring benchmark execution, b.N is adjusted until the benchmark function lasts\nlong enough to be timed reliably. The output\n\n```\nBenchmarkRandInt-8 \t68453040\t 17.8 ns/op\n\n```\nmeans that the loop ran 68453040 times at a speed of 17.8 ns per loop.\n\nIf a benchmark needs some expensive setup before running, the timer\nmay be reset:\n\n```\nfunc BenchmarkBigLen(b *testing.B) {\n big := NewBig()\n b.ResetTimer()\n for i := 0; i \u003c b.N; i++ {\n big.Len()\n }\n}\n\n```\nIf a benchmark needs to test performance in a parallel setting, it may use\nthe RunParallel helper function; such benchmarks are intended to be used with\nthe go test -cpu flag:\n\n```\nfunc BenchmarkTemplateParallel(b *testing.B) {\n templ := template.Must(template.New(\"test\").Parse(\"Hello, {{.}}!\"))\n b.RunParallel(func(pb *testing.PB) {\n var buf bytes.Buffer\n for pb.Next() {\n buf.Reset()\n templ.Execute(\u0026buf, \"World\")\n }\n })\n}\n\n```\nA detailed specification of the benchmark results format is given\nin https://golang.org/design/14313-benchmark-format.\n\nThere are standard tools for working with benchmark results at\nhttps://golang.org/x/perf/cmd.\nIn particular, https://golang.org/x/perf/cmd/benchstat performs\nstatistically robust A/B comparisons.\n\n# Examples\n\nThe package also runs and verifies example code. Example functions may\ninclude a concluding line comment that begins with \"Output:\" and is compared with\nthe standard output of the function when the tests are run. (The comparison\nignores leading and trailing space.) These are examples of an example:\n\n```\nfunc ExampleHello() {\n fmt.Println(\"hello\")\n // Output: hello\n}\n\nfunc ExampleSalutations() {\n fmt.Println(\"hello, and\")\n fmt.Println(\"goodbye\")\n // Output:\n // hello, and\n // goodbye\n}\n\n```\nThe comment prefix \"Unordered output:\" is like \"Output:\", but matches any\nline order:\n\n```\nfunc ExamplePerm() {\n for _, value := range Perm(5) {\n fmt.Println(value)\n }\n // Unordered output: 4\n // 2\n // 1\n // 3\n // 0\n}\n\n```\nExample functions without output comments are compiled but not executed.\n\nThe naming convention to declare examples for the package, a function F, a type T and\nmethod M on type T are:\n\n```\nfunc Example() { ... }\nfunc ExampleF() { ... }\nfunc ExampleT() { ... }\nfunc ExampleT_M() { ... }\n\n```\nMultiple example functions for a package/type/function/method may be provided by\nappending a distinct suffix to the name. The suffix must start with a\nlower-case letter.\n\n```\nfunc Example_suffix() { ... }\nfunc ExampleF_suffix() { ... }\nfunc ExampleT_suffix() { ... }\nfunc ExampleT_M_suffix() { ... }\n\n```\nThe entire test file is presented as the example when it contains a single\nexample function, at least one other function, type, variable, or constant\ndeclaration, and no test or benchmark functions.\n\n# Fuzzing\n\n'go test' and the testing package support fuzzing, a testing technique where\na function is called with randomly generated inputs to find bugs not\nanticipated by unit tests.\n\nFunctions of the form\n\n```\nfunc FuzzXxx(*testing.F)\n\n```\nare considered fuzz tests.\n\nFor example:\n\n```\nfunc FuzzHex(f *testing.F) {\n for _, seed := range [][]byte{{}, {0}, {9}, {0xa}, {0xf}, {1, 2, 3, 4}} {\n f.Add(seed)\n }\n f.Fuzz(func(t *testing.T, in []byte) {\n enc := hex.EncodeToString(in)\n out, err := hex.DecodeString(enc)\n if err != nil {\n t.Fatalf(\"%v: decode: %v\", in, err)\n }\n if !bytes.Equal(in, out) {\n t.Fatalf(\"%v: not equal after round trip: %v\", in, out)\n }\n })\n}\n\n```\nA fuzz test maintains a seed corpus, or a set of inputs which are run by\ndefault, and can seed input generation. Seed inputs may be registered by\ncalling (*F).Add or by storing files in the directory testdata/fuzz/\u003cName\u003e\n(where \u003cName\u003e is the name of the fuzz test) within the package containing\nthe fuzz test. Seed inputs are optional, but the fuzzing engine may find\nbugs more efficiently when provided with a set of small seed inputs with good\ncode coverage. These seed inputs can also serve as regression tests for bugs\nidentified through fuzzing.\n\nThe function passed to (*F).Fuzz within the fuzz test is considered the fuzz\ntarget. A fuzz target must accept a *T parameter, followed by one or more\nparameters for random inputs. The types of arguments passed to (*F).Add must\nbe identical to the types of these parameters. The fuzz target may signal\nthat it's found a problem the same way tests do: by calling T.Fail (or any\nmethod that calls it like T.Error or T.Fatal) or by panicking.\n\nWhen fuzzing is enabled (by setting the -fuzz flag to a regular expression\nthat matches a specific fuzz test), the fuzz target is called with arguments\ngenerated by repeatedly making random changes to the seed inputs. On\nsupported platforms, 'go test' compiles the test executable with fuzzing\ncoverage instrumentation. The fuzzing engine uses that instrumentation to\nfind and cache inputs that expand coverage, increasing the likelihood of\nfinding bugs. If the fuzz target fails for a given input, the fuzzing engine\nwrites the inputs that caused the failure to a file in the directory\ntestdata/fuzz/\u003cName\u003e within the package directory. This file later serves as\na seed input. If the file can't be written at that location (for example,\nbecause the directory is read-only), the fuzzing engine writes the file to\nthe fuzz cache directory within the build cache instead.\n\nWhen fuzzing is disabled, the fuzz target is called with the seed inputs\nregistered with F.Add and seed inputs from testdata/fuzz/\u003cName\u003e. In this\nmode, the fuzz test acts much like a regular test, with subtests started\nwith F.Fuzz instead of T.Run.\n\nSee https://go.dev/doc/fuzz for documentation about fuzzing.\n\n# Skipping\n\nTests or benchmarks may be skipped at run time with a call to\nthe Skip method of *T or *B:\n\n```\nfunc TestTimeConsuming(t *testing.T) {\n if testing.Short() {\n t.Skip(\"skipping test in short mode.\")\n }\n ...\n}\n\n```\nThe Skip method of *T can be used in a fuzz target if the input is invalid,\nbut should not be considered a failing input. For example:\n\n```\nfunc FuzzJSONMarshaling(f *testing.F) {\n f.Fuzz(func(t *testing.T, b []byte) {\n var v interface{}\n if err := json.Unmarshal(b, \u0026v); err != nil {\n t.Skip()\n }\n if _, err := json.Marshal(v); err != nil {\n t.Errorf(\"Marshal: %v\", err)\n }\n })\n}\n\n```\n# Subtests and Sub-benchmarks\n\nThe Run methods of T and B allow defining subtests and sub-benchmarks,\nwithout having to define separate functions for each. This enables uses\nlike table-driven benchmarks and creating hierarchical tests.\nIt also provides a way to share common setup and tear-down code:\n\n```\nfunc TestFoo(t *testing.T) {\n // \u003csetup code\u003e\n t.Run(\"A=1\", func(t *testing.T) { ... })\n t.Run(\"A=2\", func(t *testing.T) { ... })\n t.Run(\"B=1\", func(t *testing.T) { ... })\n // \u003ctear-down code\u003e\n}\n\n```\nEach subtest and sub-benchmark has a unique name: the combination of the name\nof the top-level test and the sequence of names passed to Run, separated by\nslashes, with an optional trailing sequence number for disambiguation.\n\nThe argument to the -run, -bench, and -fuzz command-line flags is an unanchored regular\nexpression that matches the test's name. For tests with multiple slash-separated\nelements, such as subtests, the argument is itself slash-separated, with\nexpressions matching each name element in turn. Because it is unanchored, an\nempty expression matches any string.\nFor example, using \"matching\" to mean \"whose name contains\":\n\n```\ngo test -run '' # Run all tests.\ngo test -run Foo # Run top-level tests matching \"Foo\", such as \"TestFooBar\".\ngo test -run Foo/A= # For top-level tests matching \"Foo\", run subtests matching \"A=\".\ngo test -run /A=1 # For all top-level tests, run subtests matching \"A=1\".\ngo test -fuzz FuzzFoo # Fuzz the target matching \"FuzzFoo\"\n\n```\nThe -run argument can also be used to run a specific value in the seed\ncorpus, for debugging. For example:\n\n```\ngo test -run=FuzzFoo/9ddb952d9814\n\n```\nThe -fuzz and -run flags can both be set, in order to fuzz a target but\nskip the execution of all other tests.\n\nSubtests can also be used to control parallelism. A parent test will only\ncomplete once all of its subtests complete. In this example, all tests are\nrun in parallel with each other, and only with each other, regardless of\nother top-level tests that may be defined:\n\n```\nfunc TestGroupedParallel(t *testing.T) {\n for _, tc := range tests {\n tc := tc // capture range variable\n t.Run(tc.Name, func(t *testing.T) {\n t.Parallel()\n ...\n })\n }\n}\n\n```\nRun does not return until parallel subtests have completed, providing a way\nto clean up after a group of parallel tests:\n\n```\nfunc TestTeardownParallel(t *testing.T) {\n // This Run will not return until the parallel tests finish.\n t.Run(\"group\", func(t *testing.T) {\n t.Run(\"Test1\", parallelTest1)\n t.Run(\"Test2\", parallelTest2)\n t.Run(\"Test3\", parallelTest3)\n })\n // \u003ctear-down code\u003e\n}\n\n```\n# Main\n\nIt is sometimes necessary for a test or benchmark program to do extra setup or teardown\nbefore or after it executes. It is also sometimes necessary to control\nwhich code runs on the main thread. To support these and other cases,\nif a test file contains a function:\n\n```\nfunc TestMain(m *testing.M)\n\n```\nthen the generated test will call TestMain(m) instead of running the tests or benchmarks\ndirectly. TestMain runs in the main goroutine and can do whatever setup\nand teardown is necessary around a call to m.Run. m.Run will return an exit\ncode that may be passed to os.Exit. If TestMain returns, the test wrapper\nwill pass the result of m.Run to os.Exit itself.\n\nWhen TestMain is called, flag.Parse has not been run. If TestMain depends on\ncommand-line flags, including those of the testing package, it should call\nflag.Parse explicitly. Command line flags are always parsed by the time test\nor benchmark functions run.\n\nA simple implementation of TestMain is:\n\n```\nfunc TestMain(m *testing.M) {\n\t// call flag.Parse() here if TestMain uses flags\n\tos.Exit(m.Run())\n}\n\n```\nTestMain is a low-level primitive and should not be necessary for casual\ntesting needs, where ordinary test functions suffice.\n\n[\"testing\" on pkg.go.dev](https://pkg.go.dev/testing)", "url": "https://pkg.go.dev/testing", "path": "testing", "children": [ @@ -1104,6 +1198,13 @@ "url": "https://pkg.go.dev/testing/quick", "path": "testing/quick", "children": [] + }, + { + "name": "slogtest", + "synopsis": "Package slogtest implements support for testing implementations of log/slog.Handler.\n\n[\"testing/slogtest\" on pkg.go.dev](https://pkg.go.dev/testing/slogtest)", + "url": "https://pkg.go.dev/testing/slogtest", + "path": "testing/slogtest", + "children": [] } ] }, @@ -1129,7 +1230,7 @@ }, { "name": "template", - "synopsis": "Package template implements data-driven templates for generating textual output.\n\nTo generate HTML output, see package html/template, which has the same interface\nas this package but automatically secures HTML output against certain attacks.\n\nTemplates are executed by applying them to a data structure. Annotations in the\ntemplate refer to elements of the data structure (typically a field of a struct\nor a key in a map) to control execution and derive values to be displayed.\nExecution of the template walks the structure and sets the cursor, represented\nby a period '.' and called \"dot\", to the value at the current location in the\nstructure as execution proceeds.\n\nThe input text for a template is UTF-8-encoded text in any format.\n\"Actions\"--data evaluations or control structures--are delimited by\n\"{{\" and \"}}\"; all text outside actions is copied to the output unchanged.\nExcept for raw strings, actions may not span newlines, although comments can.\n\nOnce parsed, a template may be executed safely in parallel, although if parallel\nexecutions share a Writer the output may be interleaved.\n\nHere is a trivial example that prints \"17 items are made of wool\".\n\n```\ntype Inventory struct {\n\tMaterial string\n\tCount uint\n}\nsweaters := Inventory{\"wool\", 17}\ntmpl, err := template.New(\"test\").Parse(\"{{.Count}} items are made of {{.Material}}\")\nif err != nil { panic(err) }\nerr = tmpl.Execute(os.Stdout, sweaters)\nif err != nil { panic(err) }\n\n```\nMore intricate examples appear below.\n\nText and spaces\n\nBy default, all text between actions is copied verbatim when the template is\nexecuted. For example, the string \" items are made of \" in the example above\nappears on standard output when the program is run.\n\nHowever, to aid in formatting template source code, if an action's left\ndelimiter (by default \"{{\") is followed immediately by a minus sign and white\nspace, all trailing white space is trimmed from the immediately preceding text.\nSimilarly, if the right delimiter (\"}}\") is preceded by white space and a minus\nsign, all leading white space is trimmed from the immediately following text.\nIn these trim markers, the white space must be present:\n\"{{- 3}}\" is like \"{{3}}\" but trims the immediately preceding text, while\n\"{{-3}}\" parses as an action containing the number -3.\n\nFor instance, when executing the template whose source is\n\n```\n\"{{23 -}} \u003c {{- 45}}\"\n\n```\nthe generated output would be\n\n```\n\"23\u003c45\"\n\n```\nFor this trimming, the definition of white space characters is the same as in Go:\nspace, horizontal tab, carriage return, and newline.\n\nActions\n\nHere is the list of actions. \"Arguments\" and \"pipelines\" are evaluations of\ndata, defined in detail in the corresponding sections that follow.\n\n```\n{{/* a comment */}}\n{{- /* a comment with white space trimmed from preceding and following text */ -}}\n\tA comment; discarded. May contain newlines.\n\tComments do not nest and must start and end at the\n\tdelimiters, as shown here.\n\n{{pipeline}}\n\tThe default textual representation (the same as would be\n\tprinted by fmt.Print) of the value of the pipeline is copied\n\tto the output.\n\n{{if pipeline}} T1 {{end}}\n\tIf the value of the pipeline is empty, no output is generated;\n\totherwise, T1 is executed. The empty values are false, 0, any\n\tnil pointer or interface value, and any array, slice, map, or\n\tstring of length zero.\n\tDot is unaffected.\n\n{{if pipeline}} T1 {{else}} T0 {{end}}\n\tIf the value of the pipeline is empty, T0 is executed;\n\totherwise, T1 is executed. Dot is unaffected.\n\n{{if pipeline}} T1 {{else if pipeline}} T0 {{end}}\n\tTo simplify the appearance of if-else chains, the else action\n\tof an if may include another if directly; the effect is exactly\n\tthe same as writing\n\t\t{{if pipeline}} T1 {{else}}{{if pipeline}} T0 {{end}}{{end}}\n\n{{range pipeline}} T1 {{end}}\n\tThe value of the pipeline must be an array, slice, map, or channel.\n\tIf the value of the pipeline has length zero, nothing is output;\n\totherwise, dot is set to the successive elements of the array,\n\tslice, or map and T1 is executed. If the value is a map and the\n\tkeys are of basic type with a defined order, the elements will be\n\tvisited in sorted key order.\n\n{{range pipeline}} T1 {{else}} T0 {{end}}\n\tThe value of the pipeline must be an array, slice, map, or channel.\n\tIf the value of the pipeline has length zero, dot is unaffected and\n\tT0 is executed; otherwise, dot is set to the successive elements\n\tof the array, slice, or map and T1 is executed.\n\n{{break}}\n\tThe innermost {{range pipeline}} loop is ended early, stopping the\n\tcurrent iteration and bypassing all remaining iterations.\n\n{{continue}}\n\tThe current iteration of the innermost {{range pipeline}} loop is\n\tstopped, and the loop starts the next iteration.\n\n{{template \"name\"}}\n\tThe template with the specified name is executed with nil data.\n\n{{template \"name\" pipeline}}\n\tThe template with the specified name is executed with dot set\n\tto the value of the pipeline.\n\n{{block \"name\" pipeline}} T1 {{end}}\n\tA block is shorthand for defining a template\n\t\t{{define \"name\"}} T1 {{end}}\n\tand then executing it in place\n\t\t{{template \"name\" pipeline}}\n\tThe typical use is to define a set of root templates that are\n\tthen customized by redefining the block templates within.\n\n{{with pipeline}} T1 {{end}}\n\tIf the value of the pipeline is empty, no output is generated;\n\totherwise, dot is set to the value of the pipeline and T1 is\n\texecuted.\n\n{{with pipeline}} T1 {{else}} T0 {{end}}\n\tIf the value of the pipeline is empty, dot is unaffected and T0\n\tis executed; otherwise, dot is set to the value of the pipeline\n\tand T1 is executed.\n\n```\nArguments\n\nAn argument is a simple value, denoted by one of the following.\n\n```\n- A boolean, string, character, integer, floating-point, imaginary\n or complex constant in Go syntax. These behave like Go's untyped\n constants. Note that, as in Go, whether a large integer constant\n overflows when assigned or passed to a function can depend on whether\n the host machine's ints are 32 or 64 bits.\n- The keyword nil, representing an untyped Go nil.\n- The character '.' (period):\n\t.\n The result is the value of dot.\n- A variable name, which is a (possibly empty) alphanumeric string\n preceded by a dollar sign, such as\n\t$piOver2\n or\n\t$\n The result is the value of the variable.\n Variables are described below.\n- The name of a field of the data, which must be a struct, preceded\n by a period, such as\n\t.Field\n The result is the value of the field. Field invocations may be\n chained:\n .Field1.Field2\n Fields can also be evaluated on variables, including chaining:\n $x.Field1.Field2\n- The name of a key of the data, which must be a map, preceded\n by a period, such as\n\t.Key\n The result is the map element value indexed by the key.\n Key invocations may be chained and combined with fields to any\n depth:\n .Field1.Key1.Field2.Key2\n Although the key must be an alphanumeric identifier, unlike with\n field names they do not need to start with an upper case letter.\n Keys can also be evaluated on variables, including chaining:\n $x.key1.key2\n- The name of a niladic method of the data, preceded by a period,\n such as\n\t.Method\n The result is the value of invoking the method with dot as the\n receiver, dot.Method(). Such a method must have one return value (of\n any type) or two return values, the second of which is an error.\n If it has two and the returned error is non-nil, execution terminates\n and an error is returned to the caller as the value of Execute.\n Method invocations may be chained and combined with fields and keys\n to any depth:\n .Field1.Key1.Method1.Field2.Key2.Method2\n Methods can also be evaluated on variables, including chaining:\n $x.Method1.Field\n- The name of a niladic function, such as\n\tfun\n The result is the value of invoking the function, fun(). The return\n types and values behave as in methods. Functions and function\n names are described below.\n- A parenthesized instance of one the above, for grouping. The result\n may be accessed by a field or map key invocation.\n\tprint (.F1 arg1) (.F2 arg2)\n\t(.StructValuedMethod \"arg\").Field\n\n```\nArguments may evaluate to any type; if they are pointers the implementation\nautomatically indirects to the base type when required.\nIf an evaluation yields a function value, such as a function-valued\nfield of a struct, the function is not invoked automatically, but it\ncan be used as a truth value for an if action and the like. To invoke\nit, use the call function, defined below.\n\nPipelines\n\nA pipeline is a possibly chained sequence of \"commands\". A command is a simple\nvalue (argument) or a function or method call, possibly with multiple arguments:\n\n```\nArgument\n\tThe result is the value of evaluating the argument.\n.Method [Argument...]\n\tThe method can be alone or the last element of a chain but,\n\tunlike methods in the middle of a chain, it can take arguments.\n\tThe result is the value of calling the method with the\n\targuments:\n\t\tdot.Method(Argument1, etc.)\nfunctionName [Argument...]\n\tThe result is the value of calling the function associated\n\twith the name:\n\t\tfunction(Argument1, etc.)\n\tFunctions and function names are described below.\n\n```\nA pipeline may be \"chained\" by separating a sequence of commands with pipeline\ncharacters '|'. In a chained pipeline, the result of each command is\npassed as the last argument of the following command. The output of the final\ncommand in the pipeline is the value of the pipeline.\n\nThe output of a command will be either one value or two values, the second of\nwhich has type error. If that second value is present and evaluates to\nnon-nil, execution terminates and the error is returned to the caller of\nExecute.\n\nVariables\n\nA pipeline inside an action may initialize a variable to capture the result.\nThe initialization has syntax\n\n```\n$variable := pipeline\n\n```\nwhere $variable is the name of the variable. An action that declares a\nvariable produces no output.\n\nVariables previously declared can also be assigned, using the syntax\n\n```\n$variable = pipeline\n\n```\nIf a \"range\" action initializes a variable, the variable is set to the\nsuccessive elements of the iteration. Also, a \"range\" may declare two\nvariables, separated by a comma:\n\n```\nrange $index, $element := pipeline\n\n```\nin which case $index and $element are set to the successive values of the\narray/slice index or map key and element, respectively. Note that if there is\nonly one variable, it is assigned the element; this is opposite to the\nconvention in Go range clauses.\n\nA variable's scope extends to the \"end\" action of the control structure (\"if\",\n\"with\", or \"range\") in which it is declared, or to the end of the template if\nthere is no such control structure. A template invocation does not inherit\nvariables from the point of its invocation.\n\nWhen execution begins, $ is set to the data argument passed to Execute, that is,\nto the starting value of dot.\n\nExamples\n\nHere are some example one-line templates demonstrating pipelines and variables.\nAll produce the quoted word \"output\":\n\n```\n{{\"\\\"output\\\"\"}}\n\tA string constant.\n{{`\"output\"`}}\n\tA raw string constant.\n{{printf \"%q\" \"output\"}}\n\tA function call.\n{{\"output\" | printf \"%q\"}}\n\tA function call whose final argument comes from the previous\n\tcommand.\n{{printf \"%q\" (print \"out\" \"put\")}}\n\tA parenthesized argument.\n{{\"put\" | printf \"%s%s\" \"out\" | printf \"%q\"}}\n\tA more elaborate call.\n{{\"output\" | printf \"%s\" | printf \"%q\"}}\n\tA longer chain.\n{{with \"output\"}}{{printf \"%q\" .}}{{end}}\n\tA with action using dot.\n{{with $x := \"output\" | printf \"%q\"}}{{$x}}{{end}}\n\tA with action that creates and uses a variable.\n{{with $x := \"output\"}}{{printf \"%q\" $x}}{{end}}\n\tA with action that uses the variable in another action.\n{{with $x := \"output\"}}{{$x | printf \"%q\"}}{{end}}\n\tThe same, but pipelined.\n\n```\nFunctions\n\nDuring execution functions are found in two function maps: first in the\ntemplate, then in the global function map. By default, no functions are defined\nin the template but the Funcs method can be used to add them.\n\nPredefined global functions are named as follows.\n\n```\nand\n\tReturns the boolean AND of its arguments by returning the\n\tfirst empty argument or the last argument. That is,\n\t\"and x y\" behaves as \"if x then y else x.\"\n\tEvaluation proceeds through the arguments left to right\n\tand returns when the result is determined.\ncall\n\tReturns the result of calling the first argument, which\n\tmust be a function, with the remaining arguments as parameters.\n\tThus \"call .X.Y 1 2\" is, in Go notation, dot.X.Y(1, 2) where\n\tY is a func-valued field, map entry, or the like.\n\tThe first argument must be the result of an evaluation\n\tthat yields a value of function type (as distinct from\n\ta predefined function such as print). The function must\n\treturn either one or two result values, the second of which\n\tis of type error. If the arguments don't match the function\n\tor the returned error value is non-nil, execution stops.\nhtml\n\tReturns the escaped HTML equivalent of the textual\n\trepresentation of its arguments. This function is unavailable\n\tin html/template, with a few exceptions.\nindex\n\tReturns the result of indexing its first argument by the\n\tfollowing arguments. Thus \"index x 1 2 3\" is, in Go syntax,\n\tx[1][2][3]. Each indexed item must be a map, slice, or array.\nslice\n\tslice returns the result of slicing its first argument by the\n\tremaining arguments. Thus \"slice x 1 2\" is, in Go syntax, x[1:2],\n\twhile \"slice x\" is x[:], \"slice x 1\" is x[1:], and \"slice x 1 2 3\"\n\tis x[1:2:3]. The first argument must be a string, slice, or array.\njs\n\tReturns the escaped JavaScript equivalent of the textual\n\trepresentation of its arguments.\nlen\n\tReturns the integer length of its argument.\nnot\n\tReturns the boolean negation of its single argument.\nor\n\tReturns the boolean OR of its arguments by returning the\n\tfirst non-empty argument or the last argument, that is,\n\t\"or x y\" behaves as \"if x then x else y\".\n\tEvaluation proceeds through the arguments left to right\n\tand returns when the result is determined.\nprint\n\tAn alias for fmt.Sprint\nprintf\n\tAn alias for fmt.Sprintf\nprintln\n\tAn alias for fmt.Sprintln\nurlquery\n\tReturns the escaped value of the textual representation of\n\tits arguments in a form suitable for embedding in a URL query.\n\tThis function is unavailable in html/template, with a few\n\texceptions.\n\n```\nThe boolean functions take any zero value to be false and a non-zero\nvalue to be true.\n\nThere is also a set of binary comparison operators defined as\nfunctions:\n\n```\neq\n\tReturns the boolean truth of arg1 == arg2\nne\n\tReturns the boolean truth of arg1 != arg2\nlt\n\tReturns the boolean truth of arg1 \u003c arg2\nle\n\tReturns the boolean truth of arg1 \u003c= arg2\ngt\n\tReturns the boolean truth of arg1 \u003e arg2\nge\n\tReturns the boolean truth of arg1 \u003e= arg2\n\n```\nFor simpler multi-way equality tests, eq (only) accepts two or more\narguments and compares the second and subsequent to the first,\nreturning in effect\n\n```\narg1==arg2 || arg1==arg3 || arg1==arg4 ...\n\n```\n(Unlike with || in Go, however, eq is a function call and all the\narguments will be evaluated.)\n\nThe comparison functions work on any values whose type Go defines as\ncomparable. For basic types such as integers, the rules are relaxed:\nsize and exact type are ignored, so any integer value, signed or unsigned,\nmay be compared with any other integer value. (The arithmetic value is compared,\nnot the bit pattern, so all negative integers are less than all unsigned integers.)\nHowever, as usual, one may not compare an int with a float32 and so on.\n\nAssociated templates\n\nEach template is named by a string specified when it is created. Also, each\ntemplate is associated with zero or more other templates that it may invoke by\nname; such associations are transitive and form a name space of templates.\n\nA template may use a template invocation to instantiate another associated\ntemplate; see the explanation of the \"template\" action above. The name must be\nthat of a template associated with the template that contains the invocation.\n\nNested template definitions\n\nWhen parsing a template, another template may be defined and associated with the\ntemplate being parsed. Template definitions must appear at the top level of the\ntemplate, much like global variables in a Go program.\n\nThe syntax of such definitions is to surround each template declaration with a\n\"define\" and \"end\" action.\n\nThe define action names the template being created by providing a string\nconstant. Here is a simple example:\n\n```\n`{{define \"T1\"}}ONE{{end}}\n{{define \"T2\"}}TWO{{end}}\n{{define \"T3\"}}{{template \"T1\"}} {{template \"T2\"}}{{end}}\n{{template \"T3\"}}`\n\n```\nThis defines two templates, T1 and T2, and a third T3 that invokes the other two\nwhen it is executed. Finally it invokes T3. If executed this template will\nproduce the text\n\n```\nONE TWO\n\n```\nBy construction, a template may reside in only one association. If it's\nnecessary to have a template addressable from multiple associations, the\ntemplate definition must be parsed multiple times to create distinct *Template\nvalues, or must be copied with the Clone or AddParseTree method.\n\nParse may be called multiple times to assemble the various associated templates;\nsee the ParseFiles and ParseGlob functions and methods for simple ways to parse\nrelated templates stored in files.\n\nA template may be executed directly or through ExecuteTemplate, which executes\nan associated template identified by name. To invoke our example above, we\nmight write,\n\n```\nerr := tmpl.Execute(os.Stdout, \"no data needed\")\nif err != nil {\n\tlog.Fatalf(\"execution failed: %s\", err)\n}\n\n```\nor to invoke a particular template explicitly by name,\n\n```\nerr := tmpl.ExecuteTemplate(os.Stdout, \"T2\", \"no data needed\")\nif err != nil {\n\tlog.Fatalf(\"execution failed: %s\", err)\n}\n\n[\"text/template\" on pkg.go.dev](https://pkg.go.dev/text/template)", + "synopsis": "Package template implements data-driven templates for generating textual output.\n\nTo generate HTML output, see [html/template], which has the same interface\nas this package but automatically secures HTML output against certain attacks.\n\nTemplates are executed by applying them to a data structure. Annotations in the\ntemplate refer to elements of the data structure (typically a field of a struct\nor a key in a map) to control execution and derive values to be displayed.\nExecution of the template walks the structure and sets the cursor, represented\nby a period '.' and called \"dot\", to the value at the current location in the\nstructure as execution proceeds.\n\nThe input text for a template is UTF-8-encoded text in any format.\n\"Actions\"--data evaluations or control structures--are delimited by\n\"{{\" and \"}}\"; all text outside actions is copied to the output unchanged.\n\nOnce parsed, a template may be executed safely in parallel, although if parallel\nexecutions share a Writer the output may be interleaved.\n\nHere is a trivial example that prints \"17 items are made of wool\".\n\n```\ntype Inventory struct {\n\tMaterial string\n\tCount uint\n}\nsweaters := Inventory{\"wool\", 17}\ntmpl, err := template.New(\"test\").Parse(\"{{.Count}} items are made of {{.Material}}\")\nif err != nil { panic(err) }\nerr = tmpl.Execute(os.Stdout, sweaters)\nif err != nil { panic(err) }\n\n```\nMore intricate examples appear below.\n\nText and spaces\n\nBy default, all text between actions is copied verbatim when the template is\nexecuted. For example, the string \" items are made of \" in the example above\nappears on standard output when the program is run.\n\nHowever, to aid in formatting template source code, if an action's left\ndelimiter (by default \"{{\") is followed immediately by a minus sign and white\nspace, all trailing white space is trimmed from the immediately preceding text.\nSimilarly, if the right delimiter (\"}}\") is preceded by white space and a minus\nsign, all leading white space is trimmed from the immediately following text.\nIn these trim markers, the white space must be present:\n\"{{- 3}}\" is like \"{{3}}\" but trims the immediately preceding text, while\n\"{{-3}}\" parses as an action containing the number -3.\n\nFor instance, when executing the template whose source is\n\n```\n\"{{23 -}} \u003c {{- 45}}\"\n\n```\nthe generated output would be\n\n```\n\"23\u003c45\"\n\n```\nFor this trimming, the definition of white space characters is the same as in Go:\nspace, horizontal tab, carriage return, and newline.\n\nActions\n\nHere is the list of actions. \"Arguments\" and \"pipelines\" are evaluations of\ndata, defined in detail in the corresponding sections that follow.\n\n```\n{{/* a comment */}}\n{{- /* a comment with white space trimmed from preceding and following text */ -}}\n\tA comment; discarded. May contain newlines.\n\tComments do not nest and must start and end at the\n\tdelimiters, as shown here.\n\n{{pipeline}}\n\tThe default textual representation (the same as would be\n\tprinted by fmt.Print) of the value of the pipeline is copied\n\tto the output.\n\n{{if pipeline}} T1 {{end}}\n\tIf the value of the pipeline is empty, no output is generated;\n\totherwise, T1 is executed. The empty values are false, 0, any\n\tnil pointer or interface value, and any array, slice, map, or\n\tstring of length zero.\n\tDot is unaffected.\n\n{{if pipeline}} T1 {{else}} T0 {{end}}\n\tIf the value of the pipeline is empty, T0 is executed;\n\totherwise, T1 is executed. Dot is unaffected.\n\n{{if pipeline}} T1 {{else if pipeline}} T0 {{end}}\n\tTo simplify the appearance of if-else chains, the else action\n\tof an if may include another if directly; the effect is exactly\n\tthe same as writing\n\t\t{{if pipeline}} T1 {{else}}{{if pipeline}} T0 {{end}}{{end}}\n\n{{range pipeline}} T1 {{end}}\n\tThe value of the pipeline must be an array, slice, map, or channel.\n\tIf the value of the pipeline has length zero, nothing is output;\n\totherwise, dot is set to the successive elements of the array,\n\tslice, or map and T1 is executed. If the value is a map and the\n\tkeys are of basic type with a defined order, the elements will be\n\tvisited in sorted key order.\n\n{{range pipeline}} T1 {{else}} T0 {{end}}\n\tThe value of the pipeline must be an array, slice, map, or channel.\n\tIf the value of the pipeline has length zero, dot is unaffected and\n\tT0 is executed; otherwise, dot is set to the successive elements\n\tof the array, slice, or map and T1 is executed.\n\n{{break}}\n\tThe innermost {{range pipeline}} loop is ended early, stopping the\n\tcurrent iteration and bypassing all remaining iterations.\n\n{{continue}}\n\tThe current iteration of the innermost {{range pipeline}} loop is\n\tstopped, and the loop starts the next iteration.\n\n{{template \"name\"}}\n\tThe template with the specified name is executed with nil data.\n\n{{template \"name\" pipeline}}\n\tThe template with the specified name is executed with dot set\n\tto the value of the pipeline.\n\n{{block \"name\" pipeline}} T1 {{end}}\n\tA block is shorthand for defining a template\n\t\t{{define \"name\"}} T1 {{end}}\n\tand then executing it in place\n\t\t{{template \"name\" pipeline}}\n\tThe typical use is to define a set of root templates that are\n\tthen customized by redefining the block templates within.\n\n{{with pipeline}} T1 {{end}}\n\tIf the value of the pipeline is empty, no output is generated;\n\totherwise, dot is set to the value of the pipeline and T1 is\n\texecuted.\n\n{{with pipeline}} T1 {{else}} T0 {{end}}\n\tIf the value of the pipeline is empty, dot is unaffected and T0\n\tis executed; otherwise, dot is set to the value of the pipeline\n\tand T1 is executed.\n\n```\nArguments\n\nAn argument is a simple value, denoted by one of the following.\n\n```\n- A boolean, string, character, integer, floating-point, imaginary\n or complex constant in Go syntax. These behave like Go's untyped\n constants. Note that, as in Go, whether a large integer constant\n overflows when assigned or passed to a function can depend on whether\n the host machine's ints are 32 or 64 bits.\n- The keyword nil, representing an untyped Go nil.\n- The character '.' (period):\n\t.\n The result is the value of dot.\n- A variable name, which is a (possibly empty) alphanumeric string\n preceded by a dollar sign, such as\n\t$piOver2\n or\n\t$\n The result is the value of the variable.\n Variables are described below.\n- The name of a field of the data, which must be a struct, preceded\n by a period, such as\n\t.Field\n The result is the value of the field. Field invocations may be\n chained:\n .Field1.Field2\n Fields can also be evaluated on variables, including chaining:\n $x.Field1.Field2\n- The name of a key of the data, which must be a map, preceded\n by a period, such as\n\t.Key\n The result is the map element value indexed by the key.\n Key invocations may be chained and combined with fields to any\n depth:\n .Field1.Key1.Field2.Key2\n Although the key must be an alphanumeric identifier, unlike with\n field names they do not need to start with an upper case letter.\n Keys can also be evaluated on variables, including chaining:\n $x.key1.key2\n- The name of a niladic method of the data, preceded by a period,\n such as\n\t.Method\n The result is the value of invoking the method with dot as the\n receiver, dot.Method(). Such a method must have one return value (of\n any type) or two return values, the second of which is an error.\n If it has two and the returned error is non-nil, execution terminates\n and an error is returned to the caller as the value of Execute.\n Method invocations may be chained and combined with fields and keys\n to any depth:\n .Field1.Key1.Method1.Field2.Key2.Method2\n Methods can also be evaluated on variables, including chaining:\n $x.Method1.Field\n- The name of a niladic function, such as\n\tfun\n The result is the value of invoking the function, fun(). The return\n types and values behave as in methods. Functions and function\n names are described below.\n- A parenthesized instance of one the above, for grouping. The result\n may be accessed by a field or map key invocation.\n\tprint (.F1 arg1) (.F2 arg2)\n\t(.StructValuedMethod \"arg\").Field\n\n```\nArguments may evaluate to any type; if they are pointers the implementation\nautomatically indirects to the base type when required.\nIf an evaluation yields a function value, such as a function-valued\nfield of a struct, the function is not invoked automatically, but it\ncan be used as a truth value for an if action and the like. To invoke\nit, use the call function, defined below.\n\nPipelines\n\nA pipeline is a possibly chained sequence of \"commands\". A command is a simple\nvalue (argument) or a function or method call, possibly with multiple arguments:\n\n```\nArgument\n\tThe result is the value of evaluating the argument.\n.Method [Argument...]\n\tThe method can be alone or the last element of a chain but,\n\tunlike methods in the middle of a chain, it can take arguments.\n\tThe result is the value of calling the method with the\n\targuments:\n\t\tdot.Method(Argument1, etc.)\nfunctionName [Argument...]\n\tThe result is the value of calling the function associated\n\twith the name:\n\t\tfunction(Argument1, etc.)\n\tFunctions and function names are described below.\n\n```\nA pipeline may be \"chained\" by separating a sequence of commands with pipeline\ncharacters '|'. In a chained pipeline, the result of each command is\npassed as the last argument of the following command. The output of the final\ncommand in the pipeline is the value of the pipeline.\n\nThe output of a command will be either one value or two values, the second of\nwhich has type error. If that second value is present and evaluates to\nnon-nil, execution terminates and the error is returned to the caller of\nExecute.\n\nVariables\n\nA pipeline inside an action may initialize a variable to capture the result.\nThe initialization has syntax\n\n```\n$variable := pipeline\n\n```\nwhere $variable is the name of the variable. An action that declares a\nvariable produces no output.\n\nVariables previously declared can also be assigned, using the syntax\n\n```\n$variable = pipeline\n\n```\nIf a \"range\" action initializes a variable, the variable is set to the\nsuccessive elements of the iteration. Also, a \"range\" may declare two\nvariables, separated by a comma:\n\n```\nrange $index, $element := pipeline\n\n```\nin which case $index and $element are set to the successive values of the\narray/slice index or map key and element, respectively. Note that if there is\nonly one variable, it is assigned the element; this is opposite to the\nconvention in Go range clauses.\n\nA variable's scope extends to the \"end\" action of the control structure (\"if\",\n\"with\", or \"range\") in which it is declared, or to the end of the template if\nthere is no such control structure. A template invocation does not inherit\nvariables from the point of its invocation.\n\nWhen execution begins, $ is set to the data argument passed to Execute, that is,\nto the starting value of dot.\n\nExamples\n\nHere are some example one-line templates demonstrating pipelines and variables.\nAll produce the quoted word \"output\":\n\n```\n{{\"\\\"output\\\"\"}}\n\tA string constant.\n{{`\"output\"`}}\n\tA raw string constant.\n{{printf \"%q\" \"output\"}}\n\tA function call.\n{{\"output\" | printf \"%q\"}}\n\tA function call whose final argument comes from the previous\n\tcommand.\n{{printf \"%q\" (print \"out\" \"put\")}}\n\tA parenthesized argument.\n{{\"put\" | printf \"%s%s\" \"out\" | printf \"%q\"}}\n\tA more elaborate call.\n{{\"output\" | printf \"%s\" | printf \"%q\"}}\n\tA longer chain.\n{{with \"output\"}}{{printf \"%q\" .}}{{end}}\n\tA with action using dot.\n{{with $x := \"output\" | printf \"%q\"}}{{$x}}{{end}}\n\tA with action that creates and uses a variable.\n{{with $x := \"output\"}}{{printf \"%q\" $x}}{{end}}\n\tA with action that uses the variable in another action.\n{{with $x := \"output\"}}{{$x | printf \"%q\"}}{{end}}\n\tThe same, but pipelined.\n\n```\nFunctions\n\nDuring execution functions are found in two function maps: first in the\ntemplate, then in the global function map. By default, no functions are defined\nin the template but the Funcs method can be used to add them.\n\nPredefined global functions are named as follows.\n\n```\nand\n\tReturns the boolean AND of its arguments by returning the\n\tfirst empty argument or the last argument. That is,\n\t\"and x y\" behaves as \"if x then y else x.\"\n\tEvaluation proceeds through the arguments left to right\n\tand returns when the result is determined.\ncall\n\tReturns the result of calling the first argument, which\n\tmust be a function, with the remaining arguments as parameters.\n\tThus \"call .X.Y 1 2\" is, in Go notation, dot.X.Y(1, 2) where\n\tY is a func-valued field, map entry, or the like.\n\tThe first argument must be the result of an evaluation\n\tthat yields a value of function type (as distinct from\n\ta predefined function such as print). The function must\n\treturn either one or two result values, the second of which\n\tis of type error. If the arguments don't match the function\n\tor the returned error value is non-nil, execution stops.\nhtml\n\tReturns the escaped HTML equivalent of the textual\n\trepresentation of its arguments. This function is unavailable\n\tin html/template, with a few exceptions.\nindex\n\tReturns the result of indexing its first argument by the\n\tfollowing arguments. Thus \"index x 1 2 3\" is, in Go syntax,\n\tx[1][2][3]. Each indexed item must be a map, slice, or array.\nslice\n\tslice returns the result of slicing its first argument by the\n\tremaining arguments. Thus \"slice x 1 2\" is, in Go syntax, x[1:2],\n\twhile \"slice x\" is x[:], \"slice x 1\" is x[1:], and \"slice x 1 2 3\"\n\tis x[1:2:3]. The first argument must be a string, slice, or array.\njs\n\tReturns the escaped JavaScript equivalent of the textual\n\trepresentation of its arguments.\nlen\n\tReturns the integer length of its argument.\nnot\n\tReturns the boolean negation of its single argument.\nor\n\tReturns the boolean OR of its arguments by returning the\n\tfirst non-empty argument or the last argument, that is,\n\t\"or x y\" behaves as \"if x then x else y\".\n\tEvaluation proceeds through the arguments left to right\n\tand returns when the result is determined.\nprint\n\tAn alias for fmt.Sprint\nprintf\n\tAn alias for fmt.Sprintf\nprintln\n\tAn alias for fmt.Sprintln\nurlquery\n\tReturns the escaped value of the textual representation of\n\tits arguments in a form suitable for embedding in a URL query.\n\tThis function is unavailable in html/template, with a few\n\texceptions.\n\n```\nThe boolean functions take any zero value to be false and a non-zero\nvalue to be true.\n\nThere is also a set of binary comparison operators defined as\nfunctions:\n\n```\neq\n\tReturns the boolean truth of arg1 == arg2\nne\n\tReturns the boolean truth of arg1 != arg2\nlt\n\tReturns the boolean truth of arg1 \u003c arg2\nle\n\tReturns the boolean truth of arg1 \u003c= arg2\ngt\n\tReturns the boolean truth of arg1 \u003e arg2\nge\n\tReturns the boolean truth of arg1 \u003e= arg2\n\n```\nFor simpler multi-way equality tests, eq (only) accepts two or more\narguments and compares the second and subsequent to the first,\nreturning in effect\n\n```\narg1==arg2 || arg1==arg3 || arg1==arg4 ...\n\n```\n(Unlike with || in Go, however, eq is a function call and all the\narguments will be evaluated.)\n\nThe comparison functions work on any values whose type Go defines as\ncomparable. For basic types such as integers, the rules are relaxed:\nsize and exact type are ignored, so any integer value, signed or unsigned,\nmay be compared with any other integer value. (The arithmetic value is compared,\nnot the bit pattern, so all negative integers are less than all unsigned integers.)\nHowever, as usual, one may not compare an int with a float32 and so on.\n\nAssociated templates\n\nEach template is named by a string specified when it is created. Also, each\ntemplate is associated with zero or more other templates that it may invoke by\nname; such associations are transitive and form a name space of templates.\n\nA template may use a template invocation to instantiate another associated\ntemplate; see the explanation of the \"template\" action above. The name must be\nthat of a template associated with the template that contains the invocation.\n\nNested template definitions\n\nWhen parsing a template, another template may be defined and associated with the\ntemplate being parsed. Template definitions must appear at the top level of the\ntemplate, much like global variables in a Go program.\n\nThe syntax of such definitions is to surround each template declaration with a\n\"define\" and \"end\" action.\n\nThe define action names the template being created by providing a string\nconstant. Here is a simple example:\n\n```\n{{define \"T1\"}}ONE{{end}}\n{{define \"T2\"}}TWO{{end}}\n{{define \"T3\"}}{{template \"T1\"}} {{template \"T2\"}}{{end}}\n{{template \"T3\"}}\n\n```\nThis defines two templates, T1 and T2, and a third T3 that invokes the other two\nwhen it is executed. Finally it invokes T3. If executed this template will\nproduce the text\n\n```\nONE TWO\n\n```\nBy construction, a template may reside in only one association. If it's\nnecessary to have a template addressable from multiple associations, the\ntemplate definition must be parsed multiple times to create distinct *Template\nvalues, or must be copied with the Clone or AddParseTree method.\n\nParse may be called multiple times to assemble the various associated templates;\nsee the ParseFiles and ParseGlob functions and methods for simple ways to parse\nrelated templates stored in files.\n\nA template may be executed directly or through ExecuteTemplate, which executes\nan associated template identified by name. To invoke our example above, we\nmight write,\n\n```\nerr := tmpl.Execute(os.Stdout, \"no data needed\")\nif err != nil {\n\tlog.Fatalf(\"execution failed: %s\", err)\n}\n\n```\nor to invoke a particular template explicitly by name,\n\n```\nerr := tmpl.ExecuteTemplate(os.Stdout, \"T2\", \"no data needed\")\nif err != nil {\n\tlog.Fatalf(\"execution failed: %s\", err)\n}\n\n[\"text/template\" on pkg.go.dev](https://pkg.go.dev/text/template)", "url": "https://pkg.go.dev/text/template", "path": "text/template", "children": [ @@ -1146,7 +1247,7 @@ }, { "name": "time", - "synopsis": "Package time provides functionality for measuring and displaying time.\n\nThe calendrical calculations always assume a Gregorian calendar, with\nno leap seconds.\n\nMonotonic Clocks\n\nOperating systems provide both a “wall clock,” which is subject to\nchanges for clock synchronization, and a “monotonic clock,” which is\nnot. The general rule is that the wall clock is for telling time and\nthe monotonic clock is for measuring time. Rather than split the API,\nin this package the Time returned by time.Now contains both a wall\nclock reading and a monotonic clock reading; later time-telling\noperations use the wall clock reading, but later time-measuring\noperations, specifically comparisons and subtractions, use the\nmonotonic clock reading.\n\nFor example, this code always computes a positive elapsed time of\napproximately 20 milliseconds, even if the wall clock is changed during\nthe operation being timed:\n\n```\nstart := time.Now()\n... operation that takes 20 milliseconds ...\nt := time.Now()\nelapsed := t.Sub(start)\n\n```\nOther idioms, such as time.Since(start), time.Until(deadline), and\ntime.Now().Before(deadline), are similarly robust against wall clock\nresets.\n\nThe rest of this section gives the precise details of how operations\nuse monotonic clocks, but understanding those details is not required\nto use this package.\n\nThe Time returned by time.Now contains a monotonic clock reading.\nIf Time t has a monotonic clock reading, t.Add adds the same duration to\nboth the wall clock and monotonic clock readings to compute the result.\nBecause t.AddDate(y, m, d), t.Round(d), and t.Truncate(d) are wall time\ncomputations, they always strip any monotonic clock reading from their results.\nBecause t.In, t.Local, and t.UTC are used for their effect on the interpretation\nof the wall time, they also strip any monotonic clock reading from their results.\nThe canonical way to strip a monotonic clock reading is to use t = t.Round(0).\n\nIf Times t and u both contain monotonic clock readings, the operations\nt.After(u), t.Before(u), t.Equal(u), and t.Sub(u) are carried out\nusing the monotonic clock readings alone, ignoring the wall clock\nreadings. If either t or u contains no monotonic clock reading, these\noperations fall back to using the wall clock readings.\n\nOn some systems the monotonic clock will stop if the computer goes to sleep.\nOn such a system, t.Sub(u) may not accurately reflect the actual\ntime that passed between t and u.\n\nBecause the monotonic clock reading has no meaning outside\nthe current process, the serialized forms generated by t.GobEncode,\nt.MarshalBinary, t.MarshalJSON, and t.MarshalText omit the monotonic\nclock reading, and t.Format provides no format for it. Similarly, the\nconstructors time.Date, time.Parse, time.ParseInLocation, and time.Unix,\nas well as the unmarshalers t.GobDecode, t.UnmarshalBinary.\nt.UnmarshalJSON, and t.UnmarshalText always create times with\nno monotonic clock reading.\n\nNote that the Go == operator compares not just the time instant but\nalso the Location and the monotonic clock reading. See the\ndocumentation for the Time type for a discussion of equality\ntesting for Time values.\n\nFor debugging, the result of t.String does include the monotonic\nclock reading if present. If t != u because of different monotonic clock readings,\nthat difference will be visible when printing t.String() and u.String().\n\n[\"time\" on pkg.go.dev](https://pkg.go.dev/time)", + "synopsis": "Package time provides functionality for measuring and displaying time.\n\nThe calendrical calculations always assume a Gregorian calendar, with\nno leap seconds.\n\n# Monotonic Clocks\n\nOperating systems provide both a “wall clock,” which is subject to\nchanges for clock synchronization, and a “monotonic clock,” which is\nnot. The general rule is that the wall clock is for telling time and\nthe monotonic clock is for measuring time. Rather than split the API,\nin this package the Time returned by time.Now contains both a wall\nclock reading and a monotonic clock reading; later time-telling\noperations use the wall clock reading, but later time-measuring\noperations, specifically comparisons and subtractions, use the\nmonotonic clock reading.\n\nFor example, this code always computes a positive elapsed time of\napproximately 20 milliseconds, even if the wall clock is changed during\nthe operation being timed:\n\n```\nstart := time.Now()\n... operation that takes 20 milliseconds ...\nt := time.Now()\nelapsed := t.Sub(start)\n\n```\nOther idioms, such as time.Since(start), time.Until(deadline), and\ntime.Now().Before(deadline), are similarly robust against wall clock\nresets.\n\nThe rest of this section gives the precise details of how operations\nuse monotonic clocks, but understanding those details is not required\nto use this package.\n\nThe Time returned by time.Now contains a monotonic clock reading.\nIf Time t has a monotonic clock reading, t.Add adds the same duration to\nboth the wall clock and monotonic clock readings to compute the result.\nBecause t.AddDate(y, m, d), t.Round(d), and t.Truncate(d) are wall time\ncomputations, they always strip any monotonic clock reading from their results.\nBecause t.In, t.Local, and t.UTC are used for their effect on the interpretation\nof the wall time, they also strip any monotonic clock reading from their results.\nThe canonical way to strip a monotonic clock reading is to use t = t.Round(0).\n\nIf Times t and u both contain monotonic clock readings, the operations\nt.After(u), t.Before(u), t.Equal(u), t.Compare(u), and t.Sub(u) are carried out\nusing the monotonic clock readings alone, ignoring the wall clock\nreadings. If either t or u contains no monotonic clock reading, these\noperations fall back to using the wall clock readings.\n\nOn some systems the monotonic clock will stop if the computer goes to sleep.\nOn such a system, t.Sub(u) may not accurately reflect the actual\ntime that passed between t and u.\n\nBecause the monotonic clock reading has no meaning outside\nthe current process, the serialized forms generated by t.GobEncode,\nt.MarshalBinary, t.MarshalJSON, and t.MarshalText omit the monotonic\nclock reading, and t.Format provides no format for it. Similarly, the\nconstructors time.Date, time.Parse, time.ParseInLocation, and time.Unix,\nas well as the unmarshalers t.GobDecode, t.UnmarshalBinary.\nt.UnmarshalJSON, and t.UnmarshalText always create times with\nno monotonic clock reading.\n\nThe monotonic clock reading exists only in Time values. It is not\na part of Duration values or the Unix times returned by t.Unix and\nfriends.\n\nNote that the Go == operator compares not just the time instant but\nalso the Location and the monotonic clock reading. See the\ndocumentation for the Time type for a discussion of equality\ntesting for Time values.\n\nFor debugging, the result of t.String does include the monotonic\nclock reading if present. If t != u because of different monotonic clock readings,\nthat difference will be visible when printing t.String() and u.String().\n\n[\"time\" on pkg.go.dev](https://pkg.go.dev/time)", "url": "https://pkg.go.dev/time", "path": "time", "children": [ From d5767450acbddbbfd70140424c123a9d1e7f116c Mon Sep 17 00:00:00 2001 From: x1unix Date: Mon, 8 Jan 2024 16:35:15 -0500 Subject: [PATCH 16/41] chore: bump Go and Node versions --- .github/workflows/coverage.yml | 2 +- .github/workflows/pull_request.yml | 2 +- .github/workflows/release.yml | 6 +- docs/wasm/dirlist.txt | 9 --- docs/wasm/download.txt | 90 ------------------------------ 5 files changed, 5 insertions(+), 104 deletions(-) delete mode 100644 docs/wasm/dirlist.txt delete mode 100644 docs/wasm/download.txt diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index ce6a8c87..a7ccb7e3 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -25,7 +25,7 @@ jobs: - name: Setup Go uses: actions/setup-go@v5 with: - go-version: "^1.18.0" + go-version: "^1.21.0" - uses: actions/checkout@v4 - name: Go Build Cache uses: actions/cache@v3 diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index 739841f3..1f01caa4 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -44,7 +44,7 @@ jobs: - name: Setup Go uses: actions/setup-go@v5 with: - go-version: "^1.18.0" + go-version: "^1.21.0" - name: golangci-lint uses: golangci/golangci-lint-action@v3.7.0 with: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 371edab9..00e73942 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -16,8 +16,8 @@ on: types: manual-deploy env: - GO_VERSION: 1.19 - PREV_GO_VERSION: 1.18 + GO_VERSION: 1.21.1 + PREV_GO_VERSION: 1.19 jobs: build: @@ -71,7 +71,7 @@ jobs: - uses: actions/setup-node@v4 with: - node-version: 'lts/gallium' + node-version: "lts/iron" - run: | yarn install --silent && yarn build diff --git a/docs/wasm/dirlist.txt b/docs/wasm/dirlist.txt deleted file mode 100644 index 8679c39a..00000000 --- a/docs/wasm/dirlist.txt +++ /dev/null @@ -1,9 +0,0 @@ -js: registered callback handler {value: {…}, id: 1} -fs.Open - "/go/src/main/vendor/go.uber.org/zap" -fs.Open - "/go/src/main/go.uber.org/zap" -fs.Open - "/go/src/vendor/go.uber.org/zap" -fs.Open - "/go/src/go.uber.org/zap" -fs.Open - "/go/src/vendor/go.uber.org/zap" -fs.Open - "/go/src/go.uber.org/zap" -Result: -Error: 4:2: import "go.uber.org/zap" error: unable to find source related to: "go.uber.org/zap". Either the GOPATH environment variable, or the Interpreter.Options.GoPath needs to be set \ No newline at end of file diff --git a/docs/wasm/download.txt b/docs/wasm/download.txt deleted file mode 100644 index fc97e699..00000000 --- a/docs/wasm/download.txt +++ /dev/null @@ -1,90 +0,0 @@ -{ - "Version": "v0.5.1", - "Time": "2022-05-10T13:46:14Z" -} -wasm_exec.js:22 Uncompressed: 33468 bytes -wasm_exec.js:22 Header: 504b0304 -wasm_exec.js:22 * Name: gitlab.com/qosenergy/squalus@v0.5.1/.gitlab-ci.yml -BaseName: .gitlab-ci.yml -Size: 1192 -wasm_exec.js:22 * Name: gitlab.com/qosenergy/squalus@v0.5.1/LICENSE -BaseName: LICENSE -Size: 1054 -wasm_exec.js:22 * Name: gitlab.com/qosenergy/squalus@v0.5.1/README.md -BaseName: README.md -Size: 11873 -wasm_exec.js:22 * Name: gitlab.com/qosenergy/squalus@v0.5.1/db.go -BaseName: db.go -Size: 2872 -wasm_exec.js:22 * Name: gitlab.com/qosenergy/squalus@v0.5.1/doc_test.go -BaseName: doc_test.go -Size: 3416 -wasm_exec.js:22 * Name: gitlab.com/qosenergy/squalus@v0.5.1/driver.go -BaseName: driver.go -Size: 2937 -wasm_exec.js:22 * Name: gitlab.com/qosenergy/squalus@v0.5.1/go.mod -BaseName: go.mod -Size: 604 -wasm_exec.js:22 * Name: gitlab.com/qosenergy/squalus@v0.5.1/go.sum -BaseName: go.sum -Size: 3011 -wasm_exec.js:22 * Name: gitlab.com/qosenergy/squalus@v0.5.1/mssql.go -BaseName: mssql.go -Size: 367 -wasm_exec.js:22 * Name: gitlab.com/qosenergy/squalus@v0.5.1/mssql_test.go -BaseName: mssql_test.go -Size: 2762 -wasm_exec.js:22 * Name: gitlab.com/qosenergy/squalus@v0.5.1/mysql.go -BaseName: mysql.go -Size: 1236 -wasm_exec.js:22 * Name: gitlab.com/qosenergy/squalus@v0.5.1/mysql_test.go -BaseName: mysql_test.go -Size: 2558 -wasm_exec.js:22 * Name: gitlab.com/qosenergy/squalus@v0.5.1/postgresql.go -BaseName: postgresql.go -Size: 435 -wasm_exec.js:22 * Name: gitlab.com/qosenergy/squalus@v0.5.1/postgresql_test.go -BaseName: postgresql_test.go -Size: 3486 -wasm_exec.js:22 * Name: gitlab.com/qosenergy/squalus@v0.5.1/slice_test.go -BaseName: slice_test.go -Size: 3184 -wasm_exec.js:22 * Name: gitlab.com/qosenergy/squalus@v0.5.1/sqlite.go -BaseName: sqlite.go -Size: 319 -wasm_exec.js:22 * Name: gitlab.com/qosenergy/squalus@v0.5.1/sqlite_test.go -BaseName: sqlite_test.go -Size: 1862 -wasm_exec.js:22 * Name: gitlab.com/qosenergy/squalus@v0.5.1/squalus.go -BaseName: squalus.go -Size: 6470 -wasm_exec.js:22 * Name: gitlab.com/qosenergy/squalus@v0.5.1/squalus_test.go -BaseName: squalus_test.go -Size: 13733 -wasm_exec.js:22 * Name: gitlab.com/qosenergy/squalus@v0.5.1/struct.go -BaseName: struct.go -Size: 2467 -wasm_exec.js:22 * Name: gitlab.com/qosenergy/squalus@v0.5.1/struct_convert_test.go -BaseName: struct_convert_test.go -Size: 4290 -wasm_exec.js:22 * Name: gitlab.com/qosenergy/squalus@v0.5.1/struct_test.go -BaseName: struct_test.go -Size: 5396 -wasm_exec.js:22 * Name: gitlab.com/qosenergy/squalus@v0.5.1/test/docker-compose.yml -BaseName: docker-compose.yml -Size: 583 -wasm_exec.js:22 * Name: gitlab.com/qosenergy/squalus@v0.5.1/test/gitlab-ci/Dockerfile -BaseName: Dockerfile -Size: 780 -wasm_exec.js:22 * Name: gitlab.com/qosenergy/squalus@v0.5.1/test/gitlab-ci/revive.toml -BaseName: revive.toml -Size: 987 -wasm_exec.js:22 * Name: gitlab.com/qosenergy/squalus@v0.5.1/test/test.sh -BaseName: test.sh -Size: 1138 -wasm_exec.js:22 * Name: gitlab.com/qosenergy/squalus@v0.5.1/tx.go -BaseName: tx.go -Size: 1675 -wasm_exec.js:22 * Name: gitlab.com/qosenergy/squalus@v0.5.1/tx_test.go -BaseName: tx_test.go -Size: 2716 \ No newline at end of file From 90b946e16bdd76ea348209c29b80cbb9f6eda054 Mon Sep 17 00:00:00 2001 From: x1unix Date: Mon, 8 Jan 2024 16:36:58 -0500 Subject: [PATCH 17/41] chore: update .nvmrc --- .nvmrc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.nvmrc b/.nvmrc index dbecb917..0a47c855 100644 --- a/.nvmrc +++ b/.nvmrc @@ -1 +1 @@ -v19.0.0 \ No newline at end of file +lts/iron \ No newline at end of file From e84574a1272a0f6de12aeffb87a0a1e5e13e1779 Mon Sep 17 00:00:00 2001 From: x1unix Date: Mon, 8 Jan 2024 16:41:15 -0500 Subject: [PATCH 18/41] chore: update changelog --- web/src/changelog.json | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-) diff --git a/web/src/changelog.json b/web/src/changelog.json index e6a4aef8..50bb57c4 100644 --- a/web/src/changelog.json +++ b/web/src/changelog.json @@ -1,16 +1,9 @@ { - "Interface - General": [ + "Go - WebAssembly": [ { - "issueId": 251, - "url": "/https/github.com/pull/251", - "description": "Redesign command bar to reduce number of items." - } - ], - "Interface - Hotfixes": [ - { - "issueId": 250, - "url": "/https/github.com/pull/250", - "description": "Remove broken web worker update mechanism." + "issueId": 290, + "url": "/https/github.com/issues/290", + "description": "Update Go WebAssembly compiler to 1.21" } ] } From 6c758d0d0b18ebff37bbbd4656b8337b23a09ed9 Mon Sep 17 00:00:00 2001 From: x1unix Date: Mon, 8 Jan 2024 16:43:19 -0500 Subject: [PATCH 19/41] chore: autoinstall deps --- Makefile | 1 + 1 file changed, 1 insertion(+) diff --git a/Makefile b/Makefile index 563b7b58..655e119a 100644 --- a/Makefile +++ b/Makefile @@ -28,6 +28,7 @@ run: .PHONY:ui ui: + @[ ! -d "$(UI)/node_modules" ] && yarn --cwd="$(UI)" install || true @LISTEN_ADDR=$(LISTEN_ADDR) yarn --cwd="$(UI)" start .PHONY: cover From ac8c2c81c397b2b41b79b329cf869bce88d24dbf Mon Sep 17 00:00:00 2001 From: x1unix Date: Mon, 8 Jan 2024 17:09:03 -0500 Subject: [PATCH 20/41] fix: support new Go import object namespace --- web/src/lib/go/stack/reader.ts | 10 +++--- web/src/lib/go/wrapper/interface.ts | 23 +++++++++++-- web/src/lib/go/wrapper/wrapper.ts | 50 +++++++++++++++++------------ 3 files changed, 56 insertions(+), 27 deletions(-) diff --git a/web/src/lib/go/stack/reader.ts b/web/src/lib/go/stack/reader.ts index 3084c7ed..673a73cc 100644 --- a/web/src/lib/go/stack/reader.ts +++ b/web/src/lib/go/stack/reader.ts @@ -80,7 +80,7 @@ export class StackReader { } /** - * Skip first reserved 8 bytes of stack. + * Skip first reserved 8 bytes (BP) of stack. * @returns {number} */ skipHeader() { @@ -96,7 +96,7 @@ export class StackReader { * @param typeSpec Value type * @param count number of times to repeat */ - nextN(typeSpec: AbstractTypeSpec, count: number): T[] { + nextN(typeSpec: AbstractTypeSpec, count: number): T[] { const results: any[] = []; for (let i = 0; i < count; i++) { results.push(this.next(typeSpec)); @@ -111,7 +111,7 @@ export class StackReader { * @param typeSpec Value type * @returns {*} */ - next(typeSpec: AbstractTypeSpec): T { + next(typeSpec: AbstractTypeSpec): T { if (!typeSpec) { throw new ReferenceError('StackReader.pop: missing type reader'); } @@ -136,7 +136,7 @@ export class StackReader { * Reads next `syscall/js.ref` argument and returns * JS value referenced by it. */ - nextRef(): T { + nextRef(): T { const ref = this.next(RefType); return ref.toValue(this._values) as T; } @@ -145,7 +145,7 @@ export class StackReader { * Reads next `[]syscall/js.ref` slice and * returns array of JS values. */ - nextRefSlice(): T[] { + nextRefSlice(): T[] { const refsSlice = this.next(RefSlice); return refsSlice.map(ref => ref.toValue(this._values)) as T[]; } diff --git a/web/src/lib/go/wrapper/interface.ts b/web/src/lib/go/wrapper/interface.ts index f9ca9d8b..16b2fadc 100644 --- a/web/src/lib/go/wrapper/interface.ts +++ b/web/src/lib/go/wrapper/interface.ts @@ -13,13 +13,32 @@ type ImportFunction = (sp: number) => any; type FuncWrapper = () => PendingEvent['result']; export interface ImportObject { - go: {[k: string]: ImportFunction} + /** + * Legacy Go import namespace. Used in Go 1.20.x and below. + * + * @deprecated + * **WARNING:** Since Go 1.21.x this attribute was replaced by `gojs` namespace. + * @ + */ + go: { [k: string]: ImportFunction } + + /** + * Go import namespace since Go 1.21.x. + */ + gojs: { [k: string]: ImportFunction } + + /** + * The go.test namespace. Used by `testing` package. + * + * Introduced in Go 1.21.x. + */ + _gotest: { [k: string]: ImportFunction } } export interface GoInstance { mem: DataView; argv: string[]; - env: {[k: string]: string}; + env: { [k: string]: string }; importObject: ImportObject; /** diff --git a/web/src/lib/go/wrapper/wrapper.ts b/web/src/lib/go/wrapper/wrapper.ts index 7924ccb3..bb029a10 100644 --- a/web/src/lib/go/wrapper/wrapper.ts +++ b/web/src/lib/go/wrapper/wrapper.ts @@ -1,8 +1,8 @@ import { StackReader } from "../stack"; -import { MemoryInspector} from "../debug"; -import {Bool, GoStringType, Int32} from "../types"; +import { MemoryInspector } from "../debug"; +import { Bool, GoStringType, Int32 } from "../types"; import { GoInstance, ImportObject, PendingEvent } from "./interface"; -import {Func, Ref, RefType} from "../pkg/syscall/js"; +import { Func, Ref, RefType } from "../pkg/syscall/js"; import { MemoryView } from "../memory/view"; import { @@ -10,6 +10,16 @@ import { wrapWebAssemblyInstance } from "./instance"; +/** + * Returns object which contains WebAssembly imports. + * @param go Go instance + * @returns + */ +export const getImportObject = (go: GoInstance) => ( + // Since Go 1.21, exported functions are stored in 'gojs' object. + go.importObject.gojs ?? go.importObject.go +); + /** * Wraps global namespace with specified overlay and replaces Go class instance * with a correct one. @@ -60,8 +70,8 @@ export interface Options { } export class GoWrapper { - private _inspector: MemoryInspector|null = null; - private _memView: MemoryView|null = null; + private _inspector: MemoryInspector | null = null; + private _memView: MemoryView | null = null; private _debug = false; private _debugCalls: Set; private _globalValue: object; @@ -91,7 +101,7 @@ export class GoWrapper { return this.go.mem; } - get importObject(): ImportObject { + private get importObject(): ImportObject { return this.go.importObject; } @@ -99,7 +109,7 @@ export class GoWrapper { return this.go._inst!.exports; } - constructor(parent: GoInstance, {debug = false, debugCalls, globalValue}: Options = {}) { + constructor(parent: GoInstance, { debug = false, debugCalls, globalValue }: Options = {}) { this.go = parent; this._debug = debug; this._debugCalls = new Set(debugCalls ?? []); @@ -145,7 +155,7 @@ export class GoWrapper { this.valueCall(sp, reader); }); - const wasmExitFunc = this.go.importObject.go['runtime.wasmExit']; + const wasmExitFunc = getImportObject(this.go)['runtime.wasmExit']; this.exportFunction('runtime.wasmExit', (sp, reader) => { reader.skipHeader(); const code = reader.next(Int32); @@ -279,7 +289,8 @@ export class GoWrapper { * @param func handler */ exportFunction(name: string, func: CallImportHandler) { - this.go.importObject.go[name] = this._wrapExportHandler(name, func); + const importObject = getImportObject(this.go); + importObject[name] = this._wrapExportHandler(name, func); } /** @@ -289,8 +300,7 @@ export class GoWrapper { * @returns {*} * @private */ - private _wrapExportHandler(name: string, func: CallImportHandler) - { + private _wrapExportHandler(name: string, func: CallImportHandler) { return (sp: number) => { sp >>>= 0; const isDebug = this.isCallDebuggable(name); @@ -302,7 +312,7 @@ export class GoWrapper { this.go.mem, this.go._values, sp, - {debug: isDebug} + { debug: isDebug } ); return func(sp, reader, this._memView!); @@ -313,13 +323,13 @@ export class GoWrapper { return (...args): any => { if (this._debug) { - console.log('Go._makeFuncWrapper:', { id, args }); - } + console.log('Go._makeFuncWrapper:', { id, args }); + } - const event: any = { id, this: this.go, args } - this.go._pendingEvent = event; - this.go._resume(); - return event.result; + const event: any = { id, this: this.go, args } + this.go._pendingEvent = event; + this.go._resume(); + return event.result; } } @@ -349,8 +359,8 @@ export class GoWrapper { this._memView = MemoryView.fromInstance( wrappedInstance, this.go._values, { - debug: this._debug - } + debug: this._debug + } ); const r = await this.go.run(wrappedInstance); From 48978a78057c0e1384bc0f43ea42ee63c185462e Mon Sep 17 00:00:00 2001 From: x1unix Date: Mon, 8 Jan 2024 17:12:53 -0500 Subject: [PATCH 21/41] fix: fix imports --- web/src/lib/go/wrapper/wrapper.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/web/src/lib/go/wrapper/wrapper.ts b/web/src/lib/go/wrapper/wrapper.ts index bb029a10..608ca13f 100644 --- a/web/src/lib/go/wrapper/wrapper.ts +++ b/web/src/lib/go/wrapper/wrapper.ts @@ -15,7 +15,7 @@ import { * @param go Go instance * @returns */ -export const getImportObject = (go: GoInstance) => ( +export const getImportNamespace = (go: GoInstance) => ( // Since Go 1.21, exported functions are stored in 'gojs' object. go.importObject.gojs ?? go.importObject.go ); @@ -101,7 +101,7 @@ export class GoWrapper { return this.go.mem; } - private get importObject(): ImportObject { + get importObject(): ImportObject { return this.go.importObject; } @@ -155,7 +155,7 @@ export class GoWrapper { this.valueCall(sp, reader); }); - const wasmExitFunc = getImportObject(this.go)['runtime.wasmExit']; + const wasmExitFunc = getImportNamespace(this.go)['runtime.wasmExit']; this.exportFunction('runtime.wasmExit', (sp, reader) => { reader.skipHeader(); const code = reader.next(Int32); @@ -289,7 +289,7 @@ export class GoWrapper { * @param func handler */ exportFunction(name: string, func: CallImportHandler) { - const importObject = getImportObject(this.go); + const importObject = getImportNamespace(this.go); importObject[name] = this._wrapExportHandler(name, func); } From f345ab63ea702dfb562f9f35d8ba906a9809a4db Mon Sep 17 00:00:00 2001 From: x1unix Date: Mon, 8 Jan 2024 18:56:05 -0500 Subject: [PATCH 22/41] chore: format worker.ts --- web/src/services/gorepl/worker/worker.ts | 29 ++++++++++++------------ 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/web/src/services/gorepl/worker/worker.ts b/web/src/services/gorepl/worker/worker.ts index 524e5837..19b0a309 100644 --- a/web/src/services/gorepl/worker/worker.ts +++ b/web/src/services/gorepl/worker/worker.ts @@ -4,21 +4,21 @@ import { instantiateStreaming, wrapGlobal, } from "~/lib/go"; -import {Client} from "~/lib/wrpc"; -import {registerExportObject} from "~/lib/gowasm"; +import { Client } from "~/lib/wrpc"; +import { registerExportObject } from "~/lib/gowasm"; import SyscallHelper from "~/lib/gowasm/syscall"; -import {LoggerBinding} from "~/lib/gowasm/bindings/wlog"; -import {ConsoleBinding, ConsoleStreamType} from "~/lib/gowasm/bindings/stdio"; -import {BrowserFSBinding} from "~/lib/gowasm/bindings/browserfs"; -import {PackageDBBinding} from "~/lib/gowasm/bindings/packagedb"; -import {Worker, WorkerBinding} from "~/lib/gowasm/bindings/worker"; +import { LoggerBinding } from "~/lib/gowasm/bindings/wlog"; +import { ConsoleBinding, ConsoleStreamType } from "~/lib/gowasm/bindings/stdio"; +import { BrowserFSBinding } from "~/lib/gowasm/bindings/browserfs"; +import { PackageDBBinding } from "~/lib/gowasm/bindings/packagedb"; +import { Worker, WorkerBinding } from "~/lib/gowasm/bindings/worker"; import { wrapResponseWithProgress } from "~/utils/http"; -import {FileSystemWrapper} from "~/services/go/fs"; +import { FileSystemWrapper } from "~/services/go/fs"; import ProcessStub from "~/services/go/process"; -import {PackageManagerEvent, ProgramStateChangeEvent} from "./types"; -import {PackageCacheDB, PackageFileStore, PackageIndex} from "../pkgcache"; +import { PackageManagerEvent, ProgramStateChangeEvent } from "./types"; +import { PackageCacheDB, PackageFileStore, PackageIndex } from "../pkgcache"; import { defaultWorkerConfig, GoWorkerBootEvent, @@ -28,8 +28,8 @@ import { WorkerConfig, WorkerEvent } from "./interface"; -import {UIHostBinding} from "./binding"; -import {StdioWrapper} from "./console"; +import { UIHostBinding } from "./binding"; +import { StdioWrapper } from "./console"; /** * Go WASM executable URL @@ -60,7 +60,7 @@ class BootTimeoutGuard { }); } - cancel(isStarted=true) { + cancel(isStarted = true) { this.started = isStarted; clearTimeout(this.timeout!); } @@ -147,8 +147,9 @@ export const startGoWorker = (globalScope: any, rpcClient: Client, cfg: WorkerCo }); }; + debugger; instantiateStreaming(fetchWithProgress(rpcClient, GO_WASM_URL), go.importObject) - .then(({instance}) => { + .then(({ instance }) => { rpcClient.publish(WorkerEvent.GoWorkerBoot, { eventType: GoWorkerBootEventType.Starting, }); From a365530a9c01d5a77d0099b466f98d459719571a Mon Sep 17 00:00:00 2001 From: x1unix Date: Mon, 8 Jan 2024 18:56:12 -0500 Subject: [PATCH 23/41] fix: fix imports --- internal/gorepl/uihost/downloads_js.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/gorepl/uihost/downloads_js.go b/internal/gorepl/uihost/downloads_js.go index ffcd3608..1a7f9b79 100644 --- a/internal/gorepl/uihost/downloads_js.go +++ b/internal/gorepl/uihost/downloads_js.go @@ -1,4 +1,4 @@ package uihost -//go:wasmimport gojs github.com/x1unix/go-playground/internal/gowasm/packagedb.onPackageManagerEvent +//go:wasmimport gojs github.com/x1unix/go-playground/internal/gorepl/uihost.onPackageManagerEvent func onPackageManagerEvent(e packageManagerEvent) From d440b7b9686871cdc396861558cdd20bec99e7a5 Mon Sep 17 00:00:00 2001 From: x1unix Date: Mon, 8 Jan 2024 19:04:45 -0500 Subject: [PATCH 24/41] fix: fix nil panic derefence --- internal/util/syncx/map.go | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/internal/util/syncx/map.go b/internal/util/syncx/map.go index 637fd70c..99d20712 100644 --- a/internal/util/syncx/map.go +++ b/internal/util/syncx/map.go @@ -50,7 +50,12 @@ func (m Map[K, V]) Has(item K) bool { return ok } -func (m Map[K, V]) Get(item K) (V, bool) { +func (m Map[K, V]) Get(item K) (res V, ok bool) { v, ok := m.m.Load(item) - return v.(V), ok + if !ok { + return res, false + } + + res, ok = v.(V) + return res, ok } From 0f1018a616fce15d229234e9c1c58e7fae3139a1 Mon Sep 17 00:00:00 2001 From: x1unix Date: Mon, 8 Jan 2024 19:04:57 -0500 Subject: [PATCH 25/41] fix: remove debugger stmt --- web/src/services/gorepl/worker/worker.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/web/src/services/gorepl/worker/worker.ts b/web/src/services/gorepl/worker/worker.ts index 19b0a309..6e460065 100644 --- a/web/src/services/gorepl/worker/worker.ts +++ b/web/src/services/gorepl/worker/worker.ts @@ -147,7 +147,6 @@ export const startGoWorker = (globalScope: any, rpcClient: Client, cfg: WorkerCo }); }; - debugger; instantiateStreaming(fetchWithProgress(rpcClient, GO_WASM_URL), go.importObject) .then(({ instance }) => { rpcClient.publish(WorkerEvent.GoWorkerBoot, { From cceadeddbda670197bd5605df322e910802c4417 Mon Sep 17 00:00:00 2001 From: x1unix Date: Mon, 8 Jan 2024 19:19:17 -0500 Subject: [PATCH 26/41] chore: print known callbacks --- internal/gowasm/callback.go | 2 +- internal/util/syncx/map.go | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/internal/gowasm/callback.go b/internal/gowasm/callback.go index 5156f2f9..3666ff84 100644 --- a/internal/gowasm/callback.go +++ b/internal/gowasm/callback.go @@ -82,7 +82,7 @@ func ReleaseCallback(cbId CallbackID) { func NotifyResult(cb CallbackID, result Result) { ch, ok := callbacks.Get(cb) if !ok { - panic(fmt.Sprint("gowasm: invalid callback ID: ", cb)) + panic(fmt.Sprintf("gowasm: invalid callback ID: %d. Known IDs: %d", cb, callbacks.Keys())) } wlog.Debugf("NotifyWrite: ID=%d Result=%d", cb, result) diff --git a/internal/util/syncx/map.go b/internal/util/syncx/map.go index 99d20712..aee88626 100644 --- a/internal/util/syncx/map.go +++ b/internal/util/syncx/map.go @@ -37,6 +37,15 @@ func NewMap[K comparable, V any]() Map[K, V] { } } +func (m Map[K, V]) Keys() []K { + var keys []K + m.m.Range(func(key, _ any) bool { + keys = append(keys, key.(K)) + return true + }) + return keys +} + func (m Map[K, V]) Put(key K, val V) { m.m.Store(key, val) } From 30b52c2159129918aef342ca59af353227e027d5 Mon Sep 17 00:00:00 2001 From: x1unix Date: Mon, 8 Jan 2024 19:45:31 -0500 Subject: [PATCH 27/41] fix: fix wasm imports --- internal/gowasm/packagedb/syscall_js.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/gowasm/packagedb/syscall_js.go b/internal/gowasm/packagedb/syscall_js.go index bf02bca9..58450d50 100644 --- a/internal/gowasm/packagedb/syscall_js.go +++ b/internal/gowasm/packagedb/syscall_js.go @@ -1,9 +1,9 @@ package packagedb -//go:wasmimport gojs github.com/x1unix/go-playground/internal/gowasm/packagedb.registerPackage +//go:wasmimport gojs github.com/x1unix/go-playground/internal/gowasm/packagedb.lookupPackage func lookupPackage(pkgName string, out *[]byte, cb int) -//go:wasmimport gojs github.com/x1unix/go-playground/internal/gowasm/packagedb.lookupPackage +//go:wasmimport gojs github.com/x1unix/go-playground/internal/gowasm/packagedb.registerPackage func registerPackage(pkgName, version string, cb int) //go:wasmimport gojs github.com/x1unix/go-playground/internal/gowasm/packagedb.removePackage From d4d04a74948e8015473e2112bc6325ca9d16b59d Mon Sep 17 00:00:00 2001 From: x1unix Date: Mon, 8 Jan 2024 21:16:10 -0500 Subject: [PATCH 28/41] chore: update gen command --- build.mk | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.mk b/build.mk index c56c02f7..2b4a581b 100644 --- a/build.mk +++ b/build.mk @@ -83,4 +83,4 @@ build: check-go check-yarn clean preinstall collect-meta build-server build-wasm .PHONY:gen gen: - @find . -name '*_js.go' -print0 | xargs -0 -n1 go generate + @find . -name '*_gen.go' -exec go generate -v {} \; From a5d4209f8795ae6dabd10b68e13adaeb861a24bc Mon Sep 17 00:00:00 2001 From: x1unix Date: Mon, 8 Jan 2024 21:31:09 -0500 Subject: [PATCH 29/41] feat: expose syscall/js --- internal/gorepl/runner.go | 9 +++++ internal/gorepl/symbols/env-wrap.sh | 10 +++++ internal/gorepl/symbols/go1_21_syscall_js.go | 39 ++++++++++++++++++++ internal/gorepl/symbols/symbols_gen.go | 13 +++++++ web/src/changelog.json | 5 +++ 5 files changed, 76 insertions(+) create mode 100755 internal/gorepl/symbols/env-wrap.sh create mode 100644 internal/gorepl/symbols/go1_21_syscall_js.go create mode 100644 internal/gorepl/symbols/symbols_gen.go diff --git a/internal/gorepl/runner.go b/internal/gorepl/runner.go index d865adde..1813d6c5 100644 --- a/internal/gorepl/runner.go +++ b/internal/gorepl/runner.go @@ -10,6 +10,7 @@ import ( "github.com/traefik/yaegi/interp" "github.com/traefik/yaegi/stdlib" "github.com/x1unix/go-playground/internal/gorepl/pacman" + "github.com/x1unix/go-playground/internal/gorepl/symbols" "github.com/x1unix/go-playground/internal/gowasm" "github.com/x1unix/go-playground/pkg/goproxy" ) @@ -51,6 +52,9 @@ func (w *Runner) Evaluate(ctx context.Context, code []byte) error { } vm := interp.New(interp.Options{ + BuildTags: []string{ + "wasm", "js", + }, Stderr: gowasm.Stderr, Stdout: gowasm.Stdout, GoPath: w.goPath, @@ -60,6 +64,11 @@ func (w *Runner) Evaluate(ctx context.Context, code []byte) error { return newBuildError(err, "failed to load Go runtime") } + // Load additional symbols + if err := vm.Use(symbols.Symbols); err != nil { + return newBuildError(err, "failed to load syscall/js symbols") + } + prog, err := vm.Compile(string(code)) if err != nil { return newBuildError(err, "") diff --git a/internal/gorepl/symbols/env-wrap.sh b/internal/gorepl/symbols/env-wrap.sh new file mode 100755 index 00000000..75df9f4e --- /dev/null +++ b/internal/gorepl/symbols/env-wrap.sh @@ -0,0 +1,10 @@ +#!/bin/sh + +rm go1_*.go + +# Run any incoming program with wasm/js env vars +GOOS=js GOARCH=wasm $@ + +# Update build constraints +find . -name 'go1_*.go' -exec sed -i '' 's/^\/\/go:build go1\.\([0-9]*\)/\/\/go:build go1.\1 \&\& js/g' {} \; +find . -name 'go1_*.go' -exec sed -i '' 's/^\/\/ *+build go1\.\([0-9]*\)/\/\/+build go1.\1,js/g' {} \; \ No newline at end of file diff --git a/internal/gorepl/symbols/go1_21_syscall_js.go b/internal/gorepl/symbols/go1_21_syscall_js.go new file mode 100644 index 00000000..d4bd750d --- /dev/null +++ b/internal/gorepl/symbols/go1_21_syscall_js.go @@ -0,0 +1,39 @@ +// Code generated by 'yaegi extract syscall/js'. DO NOT EDIT. + +//go:build go1.21 && js +// +build go1.21,js + +package symbols + +import ( + "reflect" + "syscall/js" +) + +func init() { + Symbols["syscall/js/js"] = map[string]reflect.Value{ + // function, constant and variable definitions + "CopyBytesToGo": reflect.ValueOf(js.CopyBytesToGo), + "CopyBytesToJS": reflect.ValueOf(js.CopyBytesToJS), + "FuncOf": reflect.ValueOf(js.FuncOf), + "Global": reflect.ValueOf(js.Global), + "Null": reflect.ValueOf(js.Null), + "TypeBoolean": reflect.ValueOf(js.TypeBoolean), + "TypeFunction": reflect.ValueOf(js.TypeFunction), + "TypeNull": reflect.ValueOf(js.TypeNull), + "TypeNumber": reflect.ValueOf(js.TypeNumber), + "TypeObject": reflect.ValueOf(js.TypeObject), + "TypeString": reflect.ValueOf(js.TypeString), + "TypeSymbol": reflect.ValueOf(js.TypeSymbol), + "TypeUndefined": reflect.ValueOf(js.TypeUndefined), + "Undefined": reflect.ValueOf(js.Undefined), + "ValueOf": reflect.ValueOf(js.ValueOf), + + // type definitions + "Error": reflect.ValueOf((*js.Error)(nil)), + "Func": reflect.ValueOf((*js.Func)(nil)), + "Type": reflect.ValueOf((*js.Type)(nil)), + "Value": reflect.ValueOf((*js.Value)(nil)), + "ValueError": reflect.ValueOf((*js.ValueError)(nil)), + } +} diff --git a/internal/gorepl/symbols/symbols_gen.go b/internal/gorepl/symbols/symbols_gen.go new file mode 100644 index 00000000..cf709e2a --- /dev/null +++ b/internal/gorepl/symbols/symbols_gen.go @@ -0,0 +1,13 @@ +// Package symbols contains additional 'syscall/js' Go symbols for Yaegi which not present by default. +package symbols + +import "reflect" + +//go:generate go run -exec ./env-wrap.sh github.com/traefik/yaegi/internal/cmd/extract syscall/js + +// Symbols variable stores the map of stdlib symbols per package. +var Symbols = map[string]map[string]reflect.Value{} + +// MapTypes variable contains a map of functions which have an interface{} as parameter but +// do something special if the parameter implements a given interface. +var MapTypes = map[reflect.Value][]reflect.Type{} diff --git a/web/src/changelog.json b/web/src/changelog.json index 50bb57c4..e3fc03ed 100644 --- a/web/src/changelog.json +++ b/web/src/changelog.json @@ -4,6 +4,11 @@ "issueId": 290, "url": "/https/github.com/issues/290", "description": "Update Go WebAssembly compiler to 1.21" + }, + { + "issueId": 292, + "url": "/https/github.com/issues/292", + "description": "Expose syscall/js package for Yaegi" } ] } From 428e2ea174ec9bc77469ae7d3eb367b1095117bd Mon Sep 17 00:00:00 2001 From: x1unix Date: Mon, 8 Jan 2024 21:37:14 -0500 Subject: [PATCH 30/41] fix: fix panic check --- internal/gorepl/handler_js.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/internal/gorepl/handler_js.go b/internal/gorepl/handler_js.go index d5bc1ff2..fc6776fe 100644 --- a/internal/gorepl/handler_js.go +++ b/internal/gorepl/handler_js.go @@ -131,7 +131,8 @@ func (h *Handler) runProgram(ctx context.Context, src []byte) { return } - if p, ok := err.(interp.Panic); ok { + var p interp.Panic + if errors.As(err, &p) { uihost.ReportEvalPanic(p.Value, p.Stack) return } From 04dce53e0c4ee7c9f7d03734e1b0c2c10aa74cb1 Mon Sep 17 00:00:00 2001 From: x1unix Date: Mon, 8 Jan 2024 21:43:04 -0500 Subject: [PATCH 31/41] chore: add localStorage debug flags --- web/src/services/gorepl/service.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/web/src/services/gorepl/service.ts b/web/src/services/gorepl/service.ts index 15095c27..eb7ef01b 100644 --- a/web/src/services/gorepl/service.ts +++ b/web/src/services/gorepl/service.ts @@ -101,6 +101,8 @@ export const getWorkerInstance = async (dispatcher: DispatchFn, stateProvider: S await client.call('init', { ...defaultWorkerConfig, + debugWasm: !!localStorage.getItem('go.debugWasm'), + debugRuntime: !!localStorage.getItem('go.debugRuntime'), env: { GOPROXY: state.settings.goProxyUrl } From c8c05a8307d9012e269aa489454392b49a7dce05 Mon Sep 17 00:00:00 2001 From: x1unix Date: Mon, 8 Jan 2024 21:46:23 -0500 Subject: [PATCH 32/41] fix: unblock run button on Go panic --- web/src/services/gorepl/service.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/web/src/services/gorepl/service.ts b/web/src/services/gorepl/service.ts index eb7ef01b..9c383a76 100644 --- a/web/src/services/gorepl/service.ts +++ b/web/src/services/gorepl/service.ts @@ -204,6 +204,7 @@ const handleProgramStateEvent = (dispatcher: DispatchFn, {state, message}: Progr Message: message!, Delay: 0, })); + dispatcher(newProgramFinishAction()); return; default: return; From 301b6a9d71042a629a3a75b1723039623a6aad3e Mon Sep 17 00:00:00 2001 From: x1unix Date: Mon, 8 Jan 2024 21:47:40 -0500 Subject: [PATCH 33/41] chore: update changelog --- web/src/changelog.json | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/web/src/changelog.json b/web/src/changelog.json index e3fc03ed..dbfec593 100644 --- a/web/src/changelog.json +++ b/web/src/changelog.json @@ -9,6 +9,11 @@ "issueId": 292, "url": "/https/github.com/issues/292", "description": "Expose syscall/js package for Yaegi" + }, + { + "issueId": 293, + "url": "/https/github.com/issues/293", + "description": "Fix UI freeze on Go program panic" } ] } From 47b42795059517ce167ca261ef9c79bb5e3925a2 Mon Sep 17 00:00:00 2001 From: x1unix Date: Mon, 8 Jan 2024 21:50:24 -0500 Subject: [PATCH 34/41] chore: update webassembly snippet --- web/src/services/go/snippets.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/src/services/go/snippets.json b/web/src/services/go/snippets.json index bb11022c..5e4825ae 100644 --- a/web/src/services/go/snippets.json +++ b/web/src/services/go/snippets.json @@ -69,7 +69,7 @@ }, { "label": "WebAssembly", - "snippet": "NCdgXZrYSk4", + "snippet": "CmRxNZQXvqB", "icon": "JS" } ], From 2ccb3eb856202e044dee40d804341bbd11277dce Mon Sep 17 00:00:00 2001 From: x1unix Date: Mon, 8 Jan 2024 22:02:23 -0500 Subject: [PATCH 35/41] chore: bump golangci-lint version --- .github/workflows/pull_request.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index 1f01caa4..5196b87b 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -48,6 +48,6 @@ jobs: - name: golangci-lint uses: golangci/golangci-lint-action@v3.7.0 with: - version: v1.52.2 + version: v1.54.2 - run: go version - run: go test ./... From fb4b509485881ab8b54278607ec94a2a80bf0e8d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 9 Jan 2024 03:04:51 +0000 Subject: [PATCH 36/41] build(deps): bump follow-redirects from 1.14.8 to 1.15.4 in /web Bumps [follow-redirects](https://github.com/follow-redirects/follow-redirects) from 1.14.8 to 1.15.4. - [Release notes](https://github.com/follow-redirects/follow-redirects/releases) - [Commits](https://github.com/follow-redirects/follow-redirects/compare/v1.14.8...v1.15.4) --- updated-dependencies: - dependency-name: follow-redirects dependency-type: indirect ... Signed-off-by: dependabot[bot] --- web/yarn.lock | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/web/yarn.lock b/web/yarn.lock index fb13586a..166d6d08 100644 --- a/web/yarn.lock +++ b/web/yarn.lock @@ -4800,9 +4800,9 @@ flatted@^3.1.0: integrity sha512-WIWGi2L3DyTUvUrwRKgGi9TwxQMUEqPOPQBVi71R96jZXJdFskXEmf54BoZaS1kknGODoIGASGEzBUYdyMCBJg== follow-redirects@^1.0.0, follow-redirects@^1.14.7: - version "1.14.8" - resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.14.8.tgz#016996fb9a11a100566398b1c6839337d7bfa8fc" - integrity sha512-1x0S9UVJHsQprFcEC/qnNzBLcIxsjAV905f/UkQxbclCsoTWlacCNOpQa/anodLl2uaEKFhfWOvM2Qg77+15zA== + version "1.15.4" + resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.15.4.tgz#cdc7d308bf6493126b17ea2191ea0ccf3e535adf" + integrity sha512-Cr4D/5wlrb0z9dgERpUL3LrmPKVDsETIJhaCMeDfuFYcqa5bldGV6wBsAN6X/vxlXQtFBMrXdXxdL8CbDTGniw== foreach@^2.0.5: version "2.0.5" From f09889f708cbd5c6bc59a48c499fccfbcdc4d0bb Mon Sep 17 00:00:00 2001 From: x1unix Date: Mon, 8 Jan 2024 22:31:09 -0500 Subject: [PATCH 37/41] chore: add stale bot --- .github/workflows/issues.yml | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 .github/workflows/issues.yml diff --git a/.github/workflows/issues.yml b/.github/workflows/issues.yml new file mode 100644 index 00000000..2810e88d --- /dev/null +++ b/.github/workflows/issues.yml @@ -0,0 +1,30 @@ +name: Close inactive issues +on: + schedule: + - cron: "30 1 * * *" + +jobs: + close-issues: + runs-on: ubuntu-latest + permissions: + issues: write + pull-requests: write + steps: + - uses: actions/stale@v5 + with: + stale-issue-label: "stale" + exempt-issue-labels: "override-stale,awaiting-feedback,question,enhancement,bug,in-progress" + exempt-pr-labels: "override-stale,in-progress" + days-before-issue-stale: 15 + days-before-issue-close: 15 + stale-issue-message: > + This issue is stale because it has been open for 15 days with no activity. + It will be closed if no further activity occurs. Thank you. + close-issue-message: > + This issue was closed because it has been inactive for 15 days since being marked as stale. + Please reopen if you'd like to work on this further. + days-before-pr-stale: 15 + days-before-pr-close: 15 + stale-pr-message: "This PR is stale because it has been open for 30 days with no activity. It will be closed if no further activity occurs. Thank you." + close-pr-message: "This PR was closed because it has been inactive for 30 days since being marked as stale. Please reopen if you'd like to work on this further." + repo-token: ${{ secrets.GITHUB_TOKEN }} From 4c5ba214eea1cd668f68e6b9232cf4a5328633c0 Mon Sep 17 00:00:00 2001 From: x1unix Date: Mon, 8 Jan 2024 22:31:47 -0500 Subject: [PATCH 38/41] chore: change issues exempt list --- .github/workflows/issues.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/issues.yml b/.github/workflows/issues.yml index 2810e88d..4a109679 100644 --- a/.github/workflows/issues.yml +++ b/.github/workflows/issues.yml @@ -13,7 +13,7 @@ jobs: - uses: actions/stale@v5 with: stale-issue-label: "stale" - exempt-issue-labels: "override-stale,awaiting-feedback,question,enhancement,bug,in-progress" + exempt-issue-labels: "override-stale,question,enhancement,bug,in-progress" exempt-pr-labels: "override-stale,in-progress" days-before-issue-stale: 15 days-before-issue-close: 15 From f6d317ba899376d6ba581aa995de104135f8cb9e Mon Sep 17 00:00:00 2001 From: x1unix Date: Tue, 9 Jan 2024 00:22:21 -0500 Subject: [PATCH 39/41] feat: introduce WASM API compatibility --- .github/workflows/release.yml | 9 ++++-- Makefile | 19 ++++++++++++- build.mk | 10 +++---- build/Dockerfile | 36 +++++++++++++++++------- build/release.dockerfile | 22 ++++++++++----- docker.mk | 6 ++++ web/src/services/api/utils.ts | 18 ++++++------ web/src/services/gorepl/worker/worker.ts | 5 ++-- web/src/store/dispatchers/build.ts | 2 +- 9 files changed, 90 insertions(+), 37 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 00e73942..8e7e48ca 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -16,7 +16,9 @@ on: types: manual-deploy env: - GO_VERSION: 1.21.1 + GO_VERSION: 1.21 + NODE_VERSION: lts/iron + WASM_API_VER: v2 PREV_GO_VERSION: 1.19 jobs: @@ -71,7 +73,7 @@ jobs: - uses: actions/setup-node@v4 with: - node-version: "lts/iron" + node-version: "${{env.NODE_VERSION}}" - run: | yarn install --silent && yarn build @@ -82,6 +84,7 @@ jobs: REACT_APP_GITHUB_URL: "${{ github.server_url }}/${{ github.repository }}" REACT_APP_GO_VERSION: "${{ env.GO_VERSION }}" REACT_APP_PREV_GO_VERSION: "${{ env.PREV_GO_VERSION }}" + REACT_APP_WASM_API_VER: "${{ env.WASM_API_VER }}" - name: Build and push image uses: docker/build-push-action@v5 @@ -92,6 +95,8 @@ jobs: tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} build-args: | + GO_VERSION=${{ env.GO_VERSION }} + WASM_API_VER=${{ env.WASM_API_VER }} APP_VERSION=${{ env.RELEASE_VERSION }} push: true diff --git a/Makefile b/Makefile index 655e119a..4d629384 100644 --- a/Makefile +++ b/Makefile @@ -6,10 +6,27 @@ GOPATH ?= $(shell go env GOPATH) PKG := ./cmd/playground UI := ./web TARGET := ./target + +# App version +APP_VERSION ?= snapshot + +# Debug mode DEBUG ?= true -GTAG ?= # Set GTAG to enable Google Analytics + +# Google Analytics ID (optional) +GTAG ?= + +# API server listen address LISTEN_ADDR := 127.0.0.1:8000 +# Repository URL for issues. +REPO_URL := $(shell git remote get-url origin | sed -e 's/:/\//' -e 's/git@/https:\/\//' -e 's/\.git//') + +# Exports +export REACT_APP_VERSION=$(APP_VERSION) +export REACT_APP_WASM_API_VER=$(WASM_API_VER) +export REACT_APP_GITHUB_URL=$(REPO_URL) + .PHONY:all all: build diff --git a/build.mk b/build.mk index 2b4a581b..b33ff76f 100644 --- a/build.mk +++ b/build.mk @@ -3,15 +3,14 @@ YARN ?= yarn GOROOT ?= $(shell $(GO) env GOROOT) TOOLS ?= ./tools PUBLIC_DIR ?= $(UI)/public -WEBWORKER_PKG ?= ./cmd/webworker -INTERPRETER_PKG ?= ./cmd/go-repl MIN_GO_VERSION ?= 1.21 +WASM_API_VER ?= v2 define build_wasm_worker @echo ":: Building WebAssembly worker '$(1)' ..." GOOS=js GOARCH=wasm $(GO) build -ldflags "-s -w" -trimpath \ - $(3) -o $(PUBLIC_DIR)/$(2) $(1) + $(3) -o $(PUBLIC_DIR)/$(2)@$(WASM_API_VER).wasm $(1) endef define check_tool @@ -21,7 +20,6 @@ define check_tool fi; endef - .PHONY: clean clean: @echo ":: Cleanup..." && rm -rf $(TARGET) && rm -rf $(UI)/build @@ -65,11 +63,11 @@ copy-wasm-exec: .PHONY:build-webworker build-webworker: - $(call build_wasm_worker,$(WEBWORKER_PKG),worker.wasm) + $(call build_wasm_worker,./cmd/webworker,worker) .PHONY:go-repl go-repl: - $(call build_wasm_worker,$(INTERPRETER_PKG),go-repl.wasm) + $(call build_wasm_worker,./cmd/go-repl,go-repl) .PHONY:build-wasm build-wasm: copy-wasm-exec build-webworker go-repl diff --git a/build/Dockerfile b/build/Dockerfile index 1ffd067f..59c3a911 100644 --- a/build/Dockerfile +++ b/build/Dockerfile @@ -1,31 +1,48 @@ -FROM node:20-alpine as ui-build -COPY web /tmp/web -WORKDIR /tmp/web +ARG NODE_VERSION=20 +ARG GO_VERSION=1.21 +ARG WASM_API_VER=v2 ARG APP_VERSION=1.0.0 ARG GITHUB_URL='https://github.com/x1unix/go-playground' +ARG PREV_GO_VERSION=1.19 + +FROM node:${NODE_VERSION}-alpine as ui-build +ARG APP_VERSION +ARG GITHUB_URL +ARG NODE_VERSION +ARG WASM_API_VER +ARG GO_VERSION +ARG PREV_GO_VERSION +COPY web /tmp/web +WORKDIR /tmp/web RUN yarn install --silent && \ REACT_APP_VERSION=$APP_VERSION \ NODE_ENV=production \ REACT_APP_GITHUB_URL=$GITHUB_URL \ REACT_APP_GO_VERSION=$GO_VERSION \ REACT_APP_PREV_GO_VERSION=$PREV_GO_VERSION \ + REACT_APP_WASM_API_VER=$WASM_API_VER \ yarn build -FROM golang:1.21-alpine as build +FROM golang:${GO_VERSION}-alpine as build +ARG GO_VERSION +ARG APP_VERSION +ARG WASM_API_VER WORKDIR /tmp/playground COPY cmd ./cmd COPY pkg ./pkg COPY internal ./internal COPY go.mod . COPY go.sum . -ARG APP_VERSION=1.0.0 RUN echo "Building server with version $APP_VERSION" && \ go build -o server -ldflags="-X 'main.Version=$APP_VERSION'" ./cmd/playground && \ - GOOS=js GOARCH=wasm go build -ldflags "-s -w" -trimpath -o ./go-repl.wasm ./cmd/go-repl && \ - GOOS=js GOARCH=wasm go build -ldflags "-s -w" -trimpath -o ./worker.wasm ./cmd/webworker && \ + GOOS=js GOARCH=wasm go build -ldflags "-s -w" -trimpath -o ./go-repl@$WASM_API_VER.wasm ./cmd/go-repl && \ + GOOS=js GOARCH=wasm go build -ldflags "-s -w" -trimpath -o ./worker@$WASM_API_VER.wasm ./cmd/webworker && \ cp $(go env GOROOT)/misc/wasm/wasm_exec.js . -FROM golang:1.21-alpine as production +FROM golang:${GO_VERSION}-alpine as production +ARG GO_VERSION +ARG APP_VERSION +ARG WASM_API_VER WORKDIR /opt/playground ENV GOROOT /usr/local/go ENV APP_CLEAN_INTERVAL=10m @@ -35,8 +52,7 @@ ENV APP_GTAG_ID='' COPY data ./data COPY --from=ui-build /tmp/web/build ./public COPY --from=build /tmp/playground/server . -COPY --from=build /tmp/playground/worker.wasm ./public -COPY --from=build /tmp/playground/go-repl.wasm ./public +COPY --from=build /tmp/playground/*.wasm ./public COPY --from=build /tmp/playground/wasm_exec.js ./public EXPOSE 8000 ENTRYPOINT /opt/playground/server \ diff --git a/build/release.dockerfile b/build/release.dockerfile index 8947e08d..460b5bbc 100644 --- a/build/release.dockerfile +++ b/build/release.dockerfile @@ -7,21 +7,29 @@ # # Use Dockerfile for simple single-arch build process -FROM golang:1.19-alpine as build +ARG GO_VERSION=1.21 +ARG APP_VERSION=1.0.0 +ARG WASM_API_VER=v2 + +FROM golang:${GO_VERSION}-alpine as build +ARG GO_VERSION +ARG WASM_API_VER +ARG APP_VERSION WORKDIR /tmp/playground COPY cmd ./cmd COPY pkg ./pkg COPY internal ./internal COPY go.mod . COPY go.sum . -ARG APP_VERSION=1.0.0 RUN echo "Building server with version $APP_VERSION" && \ go build -o server -ldflags="-X 'main.Version=$APP_VERSION'" ./cmd/playground && \ - GOOS=js GOARCH=wasm go build -ldflags "-s -w" -trimpath -o ./worker.wasm ./cmd/webworker && \ - GOOS=js GOARCH=wasm go build -ldflags "-s -w" -trimpath -o ./go-repl.wasm ./cmd/go-repl && \ + GOOS=js GOARCH=wasm go build -ldflags "-s -w" -trimpath -o ./worker@$WASM_API_VER.wasm ./cmd/webworker && \ + GOOS=js GOARCH=wasm go build -ldflags "-s -w" -trimpath -o ./go-repl@$WASM_API_VER.wasm ./cmd/go-repl && \ cp $(go env GOROOT)/misc/wasm/wasm_exec.js . -FROM golang:1.19-alpine as production +FROM golang:${GO_VERSION}-alpine as production +ARG GO_VERSION +ARG WASM_API_VER WORKDIR /opt/playground ENV GOROOT /usr/local/go ENV APP_CLEAN_INTERVAL=10m @@ -31,8 +39,8 @@ ENV APP_GTAG_ID='' COPY data ./data COPY web/build ./public COPY --from=build /tmp/playground/server . -COPY --from=build /tmp/playground/worker.wasm ./public -COPY --from=build /tmp/playground/go-repl.wasm ./public +COPY --from=build /tmp/playground/worker-$WASM_API_VER.wasm ./public +COPY --from=build /tmp/playground/go-repl-$WASM_API_VER.wasm ./public COPY --from=build /tmp/playground/wasm_exec.js ./public EXPOSE 8000 ENTRYPOINT /opt/playground/server \ diff --git a/docker.mk b/docker.mk index ba43e1fc..de2397a4 100644 --- a/docker.mk +++ b/docker.mk @@ -1,6 +1,9 @@ DOCKERFILE ?= ./build/Dockerfile IMG_NAME ?= x1unix/go-playground +GO_VERSION ?= $(MIN_GO_VERSION) +NODE_VERSION ?= 20 + .PHONY: docker docker: docker-image docker-push-image @echo ":: [✓] Done" @@ -32,4 +35,7 @@ docker-image: @echo ":: Building '$(IMG_NAME):latest' $(TAG)..." docker image build -t $(IMG_NAME):latest -t $(IMG_NAME):$(TAG) -f $(DOCKERFILE) \ --build-arg APP_VERSION=$(TAG) \ + --build-arg GO_VERSION=$(GO_VERSION) \ + --build-arg NODE_VERSION=$(NODE_VERSION) \ + --build-arg WASM_API_VER=$(WASM_API_VER) \ . diff --git a/web/src/services/api/utils.ts b/web/src/services/api/utils.ts index 4f851417..d7897430 100644 --- a/web/src/services/api/utils.ts +++ b/web/src/services/api/utils.ts @@ -1,9 +1,11 @@ +const { + REACT_APP_WASM_API_VERSION: wasmApiVersion = 'v1', + REACT_APP_WASM_BASE_URL: wasmBaseUrl = '', +} = process.env; -export const instantiateStreaming = async (resp, importObject) => { - if ('instantiateStreaming' in WebAssembly) { - return await WebAssembly.instantiateStreaming(resp, importObject); - } - - const source = await (await resp).arrayBuffer(); - return await WebAssembly.instantiate(source, importObject); -}; +/** + * Formats and returns the URL for the WASM binary. + * + * @param name + */ +export const getWasmUrl = name => `${wasmBaseUrl}/${name}@${wasmApiVersion}.wasm`; diff --git a/web/src/services/gorepl/worker/worker.ts b/web/src/services/gorepl/worker/worker.ts index 6e460065..bea5301e 100644 --- a/web/src/services/gorepl/worker/worker.ts +++ b/web/src/services/gorepl/worker/worker.ts @@ -13,6 +13,7 @@ import { BrowserFSBinding } from "~/lib/gowasm/bindings/browserfs"; import { PackageDBBinding } from "~/lib/gowasm/bindings/packagedb"; import { Worker, WorkerBinding } from "~/lib/gowasm/bindings/worker"; +import { getWasmUrl } from "~/services/api/utils"; import { wrapResponseWithProgress } from "~/utils/http"; import { FileSystemWrapper } from "~/services/go/fs"; import ProcessStub from "~/services/go/process"; @@ -34,7 +35,7 @@ import { StdioWrapper } from "./console"; /** * Go WASM executable URL */ -const GO_WASM_URL = process.env.REACT_APP_GO_WASM_URL ?? '/go-repl.wasm'; +const wasmWorkerUrl = getWasmUrl('go-repl'); export interface GoReplWorker extends Worker { runProgram(strSize: number, data: Uint8Array) @@ -147,7 +148,7 @@ export const startGoWorker = (globalScope: any, rpcClient: Client, cfg: WorkerCo }); }; - instantiateStreaming(fetchWithProgress(rpcClient, GO_WASM_URL), go.importObject) + instantiateStreaming(fetchWithProgress(rpcClient, wasmWorkerUrl), go.importObject) .then(({ instance }) => { rpcClient.publish(WorkerEvent.GoWorkerBoot, { eventType: GoWorkerBootEventType.Starting, diff --git a/web/src/store/dispatchers/build.ts b/web/src/store/dispatchers/build.ts index fcc24e4d..28ab268a 100644 --- a/web/src/store/dispatchers/build.ts +++ b/web/src/store/dispatchers/build.ts @@ -2,10 +2,10 @@ import {TargetType} from '~/services/config'; import {getWorkerInstance} from "~/services/gorepl"; import {getImportObject, goRun} from '~/services/go'; import {setTimeoutNanos, SECOND} from "~/utils/duration"; +import { instantiateStreaming } from "~/lib/go"; import client, { EvalEvent, EvalEventKind, - instantiateStreaming } from "~/services/api"; import {DispatchFn, StateProvider} from "../helpers"; From 832610fc99d86c96b98176eb05587fa71ef11365 Mon Sep 17 00:00:00 2001 From: x1unix Date: Tue, 9 Jan 2024 00:25:41 -0500 Subject: [PATCH 40/41] feat: rename repl worker file --- web/src/services/gorepl/service.ts | 2 +- web/src/workers/{go.worker.ts => repl.worker.ts} | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename web/src/workers/{go.worker.ts => repl.worker.ts} (100%) diff --git a/web/src/services/gorepl/service.ts b/web/src/services/gorepl/service.ts index 9c383a76..c6a5c1d2 100644 --- a/web/src/services/gorepl/service.ts +++ b/web/src/services/gorepl/service.ts @@ -86,7 +86,7 @@ export const getWorkerInstance = async (dispatcher: DispatchFn, stateProvider: S } })); - const worker = new Worker(new URL('../../workers/go.worker.ts', import.meta.url)); + const worker = new Worker(new URL('../../workers/repl.worker.ts', import.meta.url)); const client = new Client(worker); const state = stateProvider(); diff --git a/web/src/workers/go.worker.ts b/web/src/workers/repl.worker.ts similarity index 100% rename from web/src/workers/go.worker.ts rename to web/src/workers/repl.worker.ts From fcd5af1f2df0a2fe9fdd0090ed726562e5b3b184 Mon Sep 17 00:00:00 2001 From: x1unix Date: Tue, 9 Jan 2024 01:24:04 -0500 Subject: [PATCH 41/41] feat: unify wasm modules structure --- Makefile | 10 +-- build.mk | 26 +++--- build/Dockerfile | 12 ++- build/release.dockerfile | 15 +++- cmd/README.md | 11 +++ cmd/wasm/README.md | 13 +++ cmd/wasm/analyzer/README.md | 6 ++ cmd/{webworker => wasm/analyzer}/webworker.go | 0 cmd/wasm/api-version.txt | 1 + cmd/{ => wasm}/go-repl/main.go | 0 cmd/webworker/README.md | 6 -- web/public/worker.js | 76 ----------------- web/src/services/analyzer.ts | 4 +- web/src/services/api/utils.ts | 2 +- web/src/workers/analyzer.worker.ts | 85 +++++++++++++++++++ 15 files changed, 157 insertions(+), 110 deletions(-) create mode 100644 cmd/README.md create mode 100644 cmd/wasm/README.md create mode 100644 cmd/wasm/analyzer/README.md rename cmd/{webworker => wasm/analyzer}/webworker.go (100%) create mode 100644 cmd/wasm/api-version.txt rename cmd/{ => wasm}/go-repl/main.go (100%) delete mode 100644 cmd/webworker/README.md delete mode 100644 web/public/worker.js create mode 100644 web/src/workers/analyzer.worker.ts diff --git a/Makefile b/Makefile index 4d629384..4a375b8d 100644 --- a/Makefile +++ b/Makefile @@ -22,17 +22,17 @@ LISTEN_ADDR := 127.0.0.1:8000 # Repository URL for issues. REPO_URL := $(shell git remote get-url origin | sed -e 's/:/\//' -e 's/git@/https:\/\//' -e 's/\.git//') -# Exports -export REACT_APP_VERSION=$(APP_VERSION) -export REACT_APP_WASM_API_VER=$(WASM_API_VER) -export REACT_APP_GITHUB_URL=$(REPO_URL) - .PHONY:all all: build include build.mk include docker.mk +# Exports +export REACT_APP_VERSION=$(APP_VERSION) +export REACT_APP_WASM_API_VER=$(WASM_API_VER) +export REACT_APP_GITHUB_URL=$(REPO_URL) + .PHONY:run run: @GOROOT=$(GOROOT) $(GO) run $(PKG) \ diff --git a/build.mk b/build.mk index b33ff76f..4f1bfc65 100644 --- a/build.mk +++ b/build.mk @@ -5,12 +5,12 @@ TOOLS ?= ./tools PUBLIC_DIR ?= $(UI)/public MIN_GO_VERSION ?= 1.21 -WASM_API_VER ?= v2 +WASM_API_VER ?= $(shell cat ./cmd/wasm/api-version.txt) define build_wasm_worker @echo ":: Building WebAssembly worker '$(1)' ..." - GOOS=js GOARCH=wasm $(GO) build -ldflags "-s -w" -trimpath \ - $(3) -o $(PUBLIC_DIR)/$(2)@$(WASM_API_VER).wasm $(1) + GOOS=js GOARCH=wasm $(GO) build -buildvcs=false -ldflags "-s -w" -trimpath \ + $(2) -o $(PUBLIC_DIR)/$(1)@$(WASM_API_VER).wasm ./cmd/wasm/$(1) endef define check_tool @@ -57,23 +57,23 @@ build-ui: @echo ":: Building UI..." && \ $(YARN) --cwd="$(UI)" build -.PHONY:copy-wasm-exec -copy-wasm-exec: +.PHONY: wasm_exec.js +wasm_exec.js: @cp "$(GOROOT)/misc/wasm/wasm_exec.js" $(PUBLIC_DIR) .PHONY:build-webworker -build-webworker: - $(call build_wasm_worker,./cmd/webworker,worker) +analyzer.wasm: + $(call build_wasm_worker,analyzer) -.PHONY:go-repl -go-repl: - $(call build_wasm_worker,./cmd/go-repl,go-repl) +.PHONY:go-repl.wasm +go-repl.wasm: + $(call build_wasm_worker,go-repl) -.PHONY:build-wasm -build-wasm: copy-wasm-exec build-webworker go-repl +.PHONY:wasm +wasm: wasm_exec.js analyzer.wasm go-repl.wasm .PHONY: build -build: check-go check-yarn clean preinstall collect-meta build-server build-wasm build-ui +build: check-go check-yarn clean preinstall gen collect-meta build-server wasm build-ui @echo ":: Copying assets..." && \ cp -rfv ./data $(TARGET)/data && \ mv -v $(UI)/build $(TARGET)/public && \ diff --git a/build/Dockerfile b/build/Dockerfile index 59c3a911..d62d44ed 100644 --- a/build/Dockerfile +++ b/build/Dockerfile @@ -35,8 +35,16 @@ COPY go.mod . COPY go.sum . RUN echo "Building server with version $APP_VERSION" && \ go build -o server -ldflags="-X 'main.Version=$APP_VERSION'" ./cmd/playground && \ - GOOS=js GOARCH=wasm go build -ldflags "-s -w" -trimpath -o ./go-repl@$WASM_API_VER.wasm ./cmd/go-repl && \ - GOOS=js GOARCH=wasm go build -ldflags "-s -w" -trimpath -o ./worker@$WASM_API_VER.wasm ./cmd/webworker && \ + GOOS=js GOARCH=wasm go build \ + -buildvcs=false \ + -ldflags "-s -w" \ + -trimpath \ + -o ./go-repl@$WASM_API_VER.wasm ./cmd/wasm/go-repl && \ + GOOS=js GOARCH=wasm go build \ + -buildvcs=false \ + -ldflags "-s -w" \ + -trimpath \ + -o ./analyzer@$WASM_API_VER.wasm ./cmd/wasm/analyzer && \ cp $(go env GOROOT)/misc/wasm/wasm_exec.js . FROM golang:${GO_VERSION}-alpine as production diff --git a/build/release.dockerfile b/build/release.dockerfile index 460b5bbc..dd42214c 100644 --- a/build/release.dockerfile +++ b/build/release.dockerfile @@ -23,8 +23,16 @@ COPY go.mod . COPY go.sum . RUN echo "Building server with version $APP_VERSION" && \ go build -o server -ldflags="-X 'main.Version=$APP_VERSION'" ./cmd/playground && \ - GOOS=js GOARCH=wasm go build -ldflags "-s -w" -trimpath -o ./worker@$WASM_API_VER.wasm ./cmd/webworker && \ - GOOS=js GOARCH=wasm go build -ldflags "-s -w" -trimpath -o ./go-repl@$WASM_API_VER.wasm ./cmd/go-repl && \ + GOOS=js GOARCH=wasm go build \ + -buildvcs=false \ + -ldflags "-s -w" \ + -trimpath \ + -o ./go-repl@$WASM_API_VER.wasm ./cmd/wasm/go-repl && \ + GOOS=js GOARCH=wasm go build \ + -buildvcs=false \ + -ldflags "-s -w" \ + -trimpath \ + -o ./analyzer@$WASM_API_VER.wasm ./cmd/wasm/analyzer && \ cp $(go env GOROOT)/misc/wasm/wasm_exec.js . FROM golang:${GO_VERSION}-alpine as production @@ -39,8 +47,7 @@ ENV APP_GTAG_ID='' COPY data ./data COPY web/build ./public COPY --from=build /tmp/playground/server . -COPY --from=build /tmp/playground/worker-$WASM_API_VER.wasm ./public -COPY --from=build /tmp/playground/go-repl-$WASM_API_VER.wasm ./public +COPY --from=build /tmp/playground/*.wasm ./public COPY --from=build /tmp/playground/wasm_exec.js ./public EXPOSE 8000 ENTRYPOINT /opt/playground/server \ diff --git a/cmd/README.md b/cmd/README.md new file mode 100644 index 00000000..bceb72c7 --- /dev/null +++ b/cmd/README.md @@ -0,0 +1,11 @@ +# cmd + +This directory contains buildable project binaries. + +## playground + +The playground is a web server that serves the playground. + +## wasm + +The wasm directory contains WebAssembly binaries used on frontend side. diff --git a/cmd/wasm/README.md b/cmd/wasm/README.md new file mode 100644 index 00000000..fd2320f4 --- /dev/null +++ b/cmd/wasm/README.md @@ -0,0 +1,13 @@ +# WebAssembly Workers + +This directory contains WebAssembly worker binaries used by the playground. + +Workers can be compiled using `make wasm` command. + +## analyzer + +The analyzer is a WebAssembly worker that analyzes a given Go source file and returns errors for Monaco Editor. + +## go-repl + +The go-repl is a WebAssembly worker that interprets Go code using Yaegi Go interpreter. diff --git a/cmd/wasm/analyzer/README.md b/cmd/wasm/analyzer/README.md new file mode 100644 index 00000000..5fbb2cba --- /dev/null +++ b/cmd/wasm/analyzer/README.md @@ -0,0 +1,6 @@ +# Analyzer + +`analyzer` binary exports collection of tools used by UI web worker to analyze Go code and report +code errors. + +Package should be compiled as **WebAssembly** binary and loaded by JS WebWorker. \ No newline at end of file diff --git a/cmd/webworker/webworker.go b/cmd/wasm/analyzer/webworker.go similarity index 100% rename from cmd/webworker/webworker.go rename to cmd/wasm/analyzer/webworker.go diff --git a/cmd/wasm/api-version.txt b/cmd/wasm/api-version.txt new file mode 100644 index 00000000..8494ac27 --- /dev/null +++ b/cmd/wasm/api-version.txt @@ -0,0 +1 @@ +v2 \ No newline at end of file diff --git a/cmd/go-repl/main.go b/cmd/wasm/go-repl/main.go similarity index 100% rename from cmd/go-repl/main.go rename to cmd/wasm/go-repl/main.go diff --git a/cmd/webworker/README.md b/cmd/webworker/README.md deleted file mode 100644 index faffc45c..00000000 --- a/cmd/webworker/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# WebWorker - -`webworker` binary exports collection of tools used by UI web worker to analyze Go code and report -code errors. - -Package should be compiled as **WebAssembly** binary and loaded by JS WebWorker. \ No newline at end of file diff --git a/web/public/worker.js b/web/public/worker.js deleted file mode 100644 index 15a9ca37..00000000 --- a/web/public/worker.js +++ /dev/null @@ -1,76 +0,0 @@ -importScripts('wasm_exec.js'); - -const FN_EXIT = 'exit'; -const TYPE_ANALYZE = 'ANALYZE'; -const TYPE_EXIT = 'EXIT'; - -function wrapModule(module) { - const wrapped = { - exit: () => module.exit.call(module), - }; - Object.keys(module).filter(k => k !== FN_EXIT).forEach(fnName => { - wrapped[fnName] = (...args) => (new Promise((res, rej) => { - const cb = (rawResp) => { - try { - const resp = JSON.parse(rawResp); - if (resp.error) { - rej(new Error(`${fnName}: ${resp.error}`)); - return; - } - - res(resp.result); - } catch (ex) { - rej(new Error(`${fnName}: ${ex}`)); - } - }; - - const newArgs = args.concat(cb); - module[fnName].apply(self, newArgs); - })) - }); - return wrapped; -} - -/** - * WASM module load handler - * @param module {Object} - */ -function onModuleInit(module) { - module = wrapModule(module); - onmessage = (msg) => { - const {id, type, data} = msg.data; - switch (type) { - case TYPE_ANALYZE: - module.analyzeCode(data) - .then(result => postMessage({id, type, result})) - .catch(error => postMessage({id, type, error})); - break; - case TYPE_EXIT: - module.exit(); - break; - default: - console.error('worker: unknown message type "%s"', type); - return; - } - }; -} - -function fetchAndInstantiate(url, importObject) { - return fetch(url).then(response => - response.arrayBuffer() - ).then(bytes => - WebAssembly.instantiate(bytes, importObject) - ).then(results => - results.instance - ); -} - -function main() { - const go = new Go(); - go.argv = ['js', 'onModuleInit']; - fetchAndInstantiate("worker.wasm", go.importObject) - .then(instance => go.run(instance)) - .catch(err => console.error('worker: Go error ', err)); -} - -main(); \ No newline at end of file diff --git a/web/src/services/analyzer.ts b/web/src/services/analyzer.ts index 1736d683..55b6ab0a 100644 --- a/web/src/services/analyzer.ts +++ b/web/src/services/analyzer.ts @@ -1,8 +1,6 @@ import { v4 as uuid } from 'uuid'; import * as monaco from 'monaco-editor'; -const WORKER_PATH = '/worker.js'; - enum MessageType { Exit = 'EXIT', Analyze = 'ANALYZE' @@ -37,7 +35,7 @@ export class Analyzer { private subscriptions = new Map>(); constructor() { - this.worker = new Worker(WORKER_PATH); + this.worker = new Worker(new URL('../workers/analyzer.worker.ts', import.meta.url)); this.worker.onmessage = (m) => this.onMessage(m); } diff --git a/web/src/services/api/utils.ts b/web/src/services/api/utils.ts index d7897430..1dba78ff 100644 --- a/web/src/services/api/utils.ts +++ b/web/src/services/api/utils.ts @@ -1,5 +1,5 @@ const { - REACT_APP_WASM_API_VERSION: wasmApiVersion = 'v1', + REACT_APP_WASM_API_VER: wasmApiVersion = 'v1', REACT_APP_WASM_BASE_URL: wasmBaseUrl = '', } = process.env; diff --git a/web/src/workers/analyzer.worker.ts b/web/src/workers/analyzer.worker.ts new file mode 100644 index 00000000..4fcc5855 --- /dev/null +++ b/web/src/workers/analyzer.worker.ts @@ -0,0 +1,85 @@ +import { instantiateStreaming } from "~/lib/go/common"; +import { getWasmUrl } from "~/services/api/utils"; + +declare const self: DedicatedWorkerGlobalScope; +export default {} as typeof Worker & { new (): Worker }; + + +const FN_EXIT = 'exit'; +const TYPE_ANALYZE = 'ANALYZE'; +const TYPE_EXIT = 'EXIT'; + +self.importScripts('/wasm_exec.js'); + +function wrapModule(module) { + const wrapped = { + exit: () => module.exit.call(module), + }; + Object.keys(module) + .filter(k => k !== FN_EXIT) + .forEach(fnName => { + wrapped[fnName] = (...args) => (new Promise((res, rej) => { + const cb = (rawResp) => { + try { + const resp = JSON.parse(rawResp); + if (resp.error) { + rej(new Error(`${fnName}: ${resp.error}`)); + return; + } + + res(resp.result); + } catch (ex) { + console.error(`analyzer: "${fnName}" returned and error`, ex); + rej(new Error(`${fnName}: ${ex}`)); + } + }; + + const newArgs = args.concat(cb); + module[fnName].apply(self, newArgs); + })) + }); + return wrapped; +} + +/** + * WASM module load handler. Called by Go worker. + */ +function onModuleInit(module) { + console.log('analyzer: started'); + module = wrapModule(module); + onmessage = (msg) => { + const {id, type, data} = msg.data; + switch (type) { + case TYPE_ANALYZE: + module.analyzeCode(data) + .then(result => postMessage({id, type, result})) + .catch(error => postMessage({id, type, error})); + break; + case TYPE_EXIT: + console.log('analyzer: exit'); + module.exit(); + break; + default: + console.error('analyzer: unknown message type "%s"', type); + return; + } + }; +} + +function main() { + const workerUrl = getWasmUrl('analyzer'); + const go = new globalThis.Go(); + + // Pass the entrypoint via argv. + globalThis.onModuleInit = onModuleInit; + go.argv = ['js', 'onModuleInit']; + + fetch(workerUrl) + .then(rsp => instantiateStreaming(rsp, go.importObject)) + .then(({instance}) => + go.run(instance) + ) + .catch(err => console.error('analyzer: Go error ', err)); +} + +main();