diff --git a/Makefile b/Makefile index 1d6c8ce7..da39955b 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,5 @@ GO ?= go +UID ?= $(shell id -u) GOROOT ?= $(shell go env GOROOT) GOPATH ?= $(shell go env GOPATH) @@ -33,3 +34,9 @@ ui: cover: @cat tools/cover.txt | xargs go test -v -covermode=count -coverprofile=/tmp/cover.out && \ go tool cover -html=/tmp/cover.out + +.PHONY: install +install: + @if [ ! -d "./target" ]; then echo "ERROR: Please build project first by calling 'make'." && exit 2; fi + @if [ "$(UID)" -ne "0" ]; then echo "ERROR: you cannot perform this operation unless you are root." && exit 3; fi + @$(SHELL) ./build/install.sh diff --git a/README.md b/README.md index a34266c9..5cbbbbb4 100644 --- a/README.md +++ b/README.md @@ -34,23 +34,15 @@ See [wiki](https://github.com/x1unix/go-playground/wiki/Docker) for usage info. ### Local instance -Service can be built and run locally (**Go 1.12+** and **Node.js** required): - -``` -$ git clone https://github.com/x1unix/go-playground.git -$ cd go-playground -$ make -``` - -To run the playground, go to `target` directory and start the server: +Service can be built and run locally (**Go 1.17+** and **Node.js** required): ```bash -$ cd target -$ ./playground -f ./data/packages.json -debug +git clone https://github.com/x1unix/go-playground.git +cd go-playground +make +sudo make install ``` -Use `-help` to get information about command params - ### Third-party credits * Default playground run server provided by [play.golang.org](https://play.golang.org) diff --git a/build.mk b/build.mk index 8f62f2e1..75248426 100644 --- a/build.mk +++ b/build.mk @@ -1,4 +1,5 @@ GO ?= go +YARN ?= yarn GOROOT ?= $(shell go env GOROOT) TOOLS ?= ./tools PUBLIC_DIR ?= $(UI)/public @@ -8,6 +9,20 @@ WEBWORKER_PKG ?= ./cmd/webworker clean: @echo ":: Cleanup..." && rm -rf $(TARGET) && rm -rf $(UI)/build +.PHONY:check-go +check-go: + @if ! command -v $(GO) >/dev/null 2>&1 ; then\ + echo "ERROR: '$(GO)' binary not found. Please ensure that Go is installed or specify binary path with 'GO' variable." && \ + exit 1; \ + fi; + +.PHONY:check-yarn +check-yarn: + @if ! command -v $(YARN) >/dev/null 2>&1 ; then\ + echo "ERROR: '$(YARN)' binary not found. Please ensure that Node.js and Yarn are installed or specify binary path with 'YARN' variable." && \ + exit 1; \ + fi; + # Build targets .PHONY: collect-meta collect-meta: @@ -17,17 +32,17 @@ collect-meta: .PHONY:preinstall preinstall: @echo ":: Checking and installing dependencies..." && \ - cd $(UI) && yarn install --silent + cd $(UI) && $(YARN) install --silent .PHONY:build-server build-server: @echo ":: Building server..." && \ - go build -o $(TARGET)/playground $(PKG) + $(GO) build -o $(TARGET)/playground $(PKG) .PHONY:build-ui build-ui: @echo ":: Building UI..." && \ - cd $(UI) && yarn build + cd $(UI) && $(YARN) build .PHONY:build-webworker build-webworker: @@ -36,7 +51,7 @@ build-webworker: cp "$(GOROOT)/misc/wasm/wasm_exec.js" $(PUBLIC_DIR) .PHONY: build -build: clean preinstall collect-meta build-server build-webworker build-ui +build: check-go check-yarn clean preinstall collect-meta build-server build-webworker build-ui @echo ":: Copying assets..." && \ cp -rfv ./data $(TARGET)/data && \ mv -v $(UI)/build $(TARGET)/public && \ diff --git a/build/better-go-playground.service b/build/better-go-playground.service new file mode 100644 index 00000000..5a85342c --- /dev/null +++ b/build/better-go-playground.service @@ -0,0 +1,17 @@ +[Unit] +Description=Better Go Playground +After=network.target +StartLimitIntervalSec=10 +StartLimitBurst=5 + +[Service] +Type=simple +User=go-playground +WorkingDirectory=/opt/better-go-playground +ExecStart=/opt/better-go-playground/playground -f /opt/better-playground/data/packages.json +Restart=on-failure +LimitNOFILE=1048576 +RestartSec=5 + +[Install] +WantedBy=multi-user.target diff --git a/build/go-playground.service b/build/go-playground.service deleted file mode 100644 index a2201e06..00000000 --- a/build/go-playground.service +++ /dev/null @@ -1,17 +0,0 @@ -[Unit] -Description=go-playground -After=network.target - -[Service] -Type=notify -User=go-playground -WorkingDirectory=/home/go-playground -Environment=GOROOT=/usr/local/go -ExecStart=/home/go-playground/target/playground -f ./data/packages.json -debug -ExecReload=/bin/kill -HUP $MAINPID -Restart=on-failure -LimitNOFILE=1048576 -NotifyAccess=main - -[Install] -WantedBy=multi-user.target diff --git a/build/install.sh b/build/install.sh new file mode 100755 index 00000000..42444f76 --- /dev/null +++ b/build/install.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env sh +set -e + +SVC_NAME='better-go-playground' +SVC_USER='go-playground' +DST_DIR='/opt/go-playground' + +if [ "$(uname -s)" != "Linux" ]; then + echo "ERROR: This installation script doesn't support $(uname -s). Only Linux systems are supported." + exit 4 +fi + +echo ":: Creating a user '$SVC_USER'..." +useradd -m --system go-playground + +echo ":: Copying files..." +cp -rfv ./target "$DST_DIR" +chown -R -v "$SVC_USER:$SVC_USER" "$DST_DIR" +chmod +x "$DST_DIR/playground" + +echo ":: Installing service..." +cp -fv "./build/$SVC_NAME.service" /etc/systemd/system +systemctl daemon reload + +echo ":: Starting service..." +systemctl enable --now "$SVC_NAME" + +echo "Installation finished. Use 'systemctl start|stop|restart|status $SVC_NAME' to start, stop or restart the service." diff --git a/data/packages.json b/data/packages.json index e3408866..38c9243e 100644 --- a/data/packages.json +++ b/data/packages.json @@ -157,7 +157,7 @@ }, { "name": "ecdsa", - "synopsis": "Package ecdsa implements the Elliptic Curve Digital Signature Algorithm, as\ndefined in FIPS 186-3.\n\nThis implementation derives the nonce from an AES-CTR CSPRNG keyed by:\n\nSHA2-512(priv.D || entropy || hash)[:32]\n\nThe CSPRNG key is indifferentiable from a random oracle as shown in\n[Coron], the AES-CTR stream is indifferentiable from a random oracle\nunder standard cryptographic assumptions (see [Larsson] for examples).\n\nReferences:\n [Coron]\n https://cs.nyu.edu/~dodis/ps/merkle.pdf\n [Larsson]\n https://www.nada.kth.se/kurser/kth/2D1441/semteo03/lecturenotes/assump.pdf\n\n[\"crypto/ecdsa\" on pkg.go.dev](https://pkg.go.dev/crypto/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)", "url": "https://pkg.go.dev/crypto/ecdsa", "path": "crypto/ecdsa", "children": [] @@ -171,7 +171,7 @@ }, { "name": "elliptic", - "synopsis": "Package elliptic implements several standard elliptic curves over prime\nfields.\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\n[\"crypto/elliptic\" on pkg.go.dev](https://pkg.go.dev/crypto/elliptic)", "url": "https://pkg.go.dev/crypto/elliptic", "path": "crypto/elliptic", "children": [] @@ -248,7 +248,7 @@ }, { "name": "x509", - "synopsis": "Package x509 parses X.509-encoded keys and certificates.\n\n[\"crypto/x509\" on pkg.go.dev](https://pkg.go.dev/crypto/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)", "url": "https://pkg.go.dev/crypto/x509", "path": "crypto/x509", "children": [ @@ -292,6 +292,13 @@ "url": "https://pkg.go.dev/debug", "path": "debug", "children": [ + { + "name": "buildinfo", + "synopsis": "Package buildinfo provides access to information embedded in a Go binary\nabout how it was built. This includes the Go toolchain version, and the\nset of modules used (for binaries built in module mode).\n\nBuild information is available for the currently running binary in\nruntime/debug.ReadBuildInfo.\n\n[\"debug/buildinfo\" on pkg.go.dev](https://pkg.go.dev/debug/buildinfo)", + "url": "https://pkg.go.dev/debug/buildinfo", + "path": "debug/buildinfo", + "children": [] + }, { "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)", @@ -338,7 +345,7 @@ }, { "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.\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 global variables at package scope,\nnot 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```\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)", "url": "https://pkg.go.dev/embed", "path": "embed", "children": [] @@ -451,7 +458,7 @@ }, { "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": "```\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)", "url": "https://pkg.go.dev/fmt", "path": "fmt", "children": [] @@ -471,7 +478,7 @@ }, { "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// +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\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)", "url": "https://pkg.go.dev/go/build", "path": "go/build", "children": [ @@ -739,7 +746,7 @@ }, { "name": "rand", - "synopsis": "Package rand implements pseudo-random number generators.\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\nMathematical interval notation such as [0, n) is used throughout the\ndocumentation for this package.\n\nFor random numbers suitable for security-sensitive work, see the crypto/rand\npackage.\n\n[\"math/rand\" on pkg.go.dev](https://pkg.go.dev/math/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)", "url": "https://pkg.go.dev/math/rand", "path": "math/rand", "children": [] @@ -824,7 +831,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```\nwget -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```\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)", "url": "https://pkg.go.dev/net/http/pprof", "path": "net/http/pprof", "children": [] @@ -838,6 +845,13 @@ "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)", + "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)", @@ -891,14 +905,14 @@ }, { "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 GNU/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. Also, the Go standard library expects that any signal handlers\nwill use the SA_RESTART flag. Failing to do so may cause some library\ncalls to return \"interrupted system call\" errors.\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 GNU/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\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)", "url": "https://pkg.go.dev/os/signal", "path": "os/signal", "children": [] }, { "name": "user", - "synopsis": "Package user allows user account lookups by name or id.\n\nFor most Unix systems, this package has two internal implementations of\nresolving user and group ids to names. One is written in pure Go and\nparses /etc/passwd and /etc/group. The other is cgo-based and relies on\nthe standard C library (libc) routines such as getpwuid_r and getgrnam_r.\n\nWhen cgo is available, cgo-based (libc-backed) code is used by default.\nThis can be overridden by using osusergo build tag, which enforces\nthe pure Go implementation.\n\n[\"os/user\" on pkg.go.dev](https://pkg.go.dev/os/user)", + "synopsis": "Package user allows user account lookups by name or id.\n\nFor most Unix systems, this package has two internal implementations of\nresolving user and group ids to names, and listing supplementary group IDs.\nOne is written in pure Go and parses /etc/passwd and /etc/group. The other\nis cgo-based and relies on the standard C library (libc) routines such as\ngetpwuid_r, getgrnam_r, and getgrouplist.\n\nWhen cgo is available, and the required routines are implemented in libc\nfor a particular platform, cgo-based (libc-backed) code is used.\nThis can be overridden by using osusergo build tag, which enforces\nthe pure Go implementation.\n\n[\"os/user\" on pkg.go.dev](https://pkg.go.dev/os/user)", "url": "https://pkg.go.dev/os/user", "path": "os/user", "children": [] @@ -936,7 +950,7 @@ }, { "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.\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\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 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)", "url": "https://pkg.go.dev/regexp", "path": "regexp", "children": [ @@ -951,10 +965,17 @@ }, { "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\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\nscavenge: scavenge=1 enables debugging mode of heap scavenger.\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, net/http, and crypto/tls 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\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)", "url": "https://pkg.go.dev/runtime", "path": "runtime", "children": [ + { + "name": "asan", + "synopsis": "\n[\"runtime/asan\" on pkg.go.dev](https://pkg.go.dev/runtime/asan)", + "url": "https://pkg.go.dev/runtime/asan", + "path": "runtime/asan", + "children": [] + }, { "name": "cgo", "synopsis": "Package cgo contains runtime support for code generated\nby the cgo tool. See the documentation for the cgo command\nfor details on using cgo.\n\n[\"runtime/cgo\" on pkg.go.dev](https://pkg.go.dev/runtime/cgo)", @@ -971,7 +992,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 all objects allocated by approximate size.\n\n/gc/heap/frees-by-size:bytes\n\tDistribution of all objects freed by approximate size.\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/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[\"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\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)", "url": "https://pkg.go.dev/runtime/metrics", "path": "runtime/metrics", "children": [] @@ -1059,7 +1080,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\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\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\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 and -bench 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\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 8192 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 program to do extra setup or teardown\nbefore or after testing. It is also sometimes necessary for a test 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\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[\"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 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)", "url": "https://pkg.go.dev/testing", "path": "testing", "children": [ @@ -1108,7 +1129,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{{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\". All the\n\targuments are evaluated.\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\". All the\n\targuments are evaluated.\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 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)", "url": "https://pkg.go.dev/text/template", "path": "text/template", "children": [