================ CODE SNIPPETS ================ TITLE: List Go Examples using 'go test -list' DESCRIPTION: This snippet illustrates how to list all functions starting with 'Example' in a Go project. The command 'go test -list=Example' is executed, and expected output includes 'Example_simple' and 'Example_withEmptyOutput'. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/list_test_simple.txt#_snippet_2 LANGUAGE: bash CODE: ``` go test -list=Example stdout Example_simple stdout Example_withEmptyOutput ``` -------------------------------- TITLE: Install Go Module Executable DESCRIPTION: Compiles and installs the specified module as an executable. The binary is placed in the Go bin directory. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/version_replace.txt#_snippet_2 LANGUAGE: go CODE: ``` go install example.com/printversion ``` -------------------------------- TITLE: Go Get: Remove Dependencies with '@none' DESCRIPTION: This example shows how to remove all modules matching a wildcard pattern using '@none' with 'go get'. It fetches all packages under 'example.net' with '@none' and verifies that no dependencies matching the prefix remain in the module list. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/mod_get_split.txt#_snippet_6 LANGUAGE: bash CODE: ``` go get example.net/... go get example.net/... go list -m all ! stdout '^example.net' ``` -------------------------------- TITLE: Configuring Go Project Structure and Dependencies DESCRIPTION: Sets up Go package directories, copies source files and pre-compiled archives, and installs a package using 'go install -x'. This tests how the Go toolchain resolves dependencies based on GOPATH. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/build_gopath_order.txt#_snippet_1 LANGUAGE: bash CODE: ``` mkdir $WORK/p1/src/foo $WORK/p2/src/baz mkdir $WORK/p2/pkg/${GOOS}_${GOARCH} $WORK/p1/src/bar cp foo.go $WORK/p1/src/foo/foo.go cp baz.go $WORK/p2/src/baz/baz.go cp foo.a $WORK/p2/pkg/${GOOS}_${GOARCH}/foo.a cp bar.go $WORK/p1/src/bar/bar.go go install -x bar ``` -------------------------------- TITLE: Installing and Testing Test2JSON Tool DESCRIPTION: This code snippet focuses on installing the 'test2json' tool into the Go environment and verifying its successful installation and execution. It checks for the tool's existence in the correct directory and confirms its output when run. It also verifies that the 'go tool -n test2json' command points to the newly installed tool. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/tool_build_as_needed.txt#_snippet_2 LANGUAGE: bash CODE: ``` # GOROOT with test2json uses the test2json in the GOROOT go install cmd/test2json exists $TOOLDIR/test2json$GOEXE go tool test2json stdout '{"Action":"start"}' go tool -n test2json stdout $NEWTOOLDIR${/}test2json$GOEXE ``` -------------------------------- TITLE: Install Go Module with Specific Version DESCRIPTION: Uses the 'go get' command to download and install a specific version of a Go module. This is a common way to manage dependencies in Go projects. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/badgo.txt#_snippet_0 LANGUAGE: bash CODE: ``` go get example.net/badgo@v1.0.0 go get example.net/badgo@v1.1.0 go get example.net/badgo@v1.2.0 go get example.net/badgo@v1.3.0 go get example.net/badgo@v1.4.0 go get example.net/badgo@v1.5.0 go get example.net/badgo@v1.6.0 ``` -------------------------------- TITLE: Install echo command for Windows DESCRIPTION: Installs the 'echo' command for Windows environments where it's not natively available. It sets the GOBIN environment variable and then uses 'go install' to install 'echo.go'. Finally, it updates the PATH to include the new GOBIN directory. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/generate.txt#_snippet_0 LANGUAGE: bash CODE: ``` env GOBIN=$WORK/tmp/bin go install echo.go env PATH=$GOBIN:${:}$PATH ``` -------------------------------- TITLE: Go Work File Example DESCRIPTION: This is an example content of a go.work file, specifying the Go version and the local workspace. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/work_get_toolchain.txt#_snippet_2 LANGUAGE: go.work CODE: ``` go 1.18 use . ``` -------------------------------- TITLE: Go Module Workspace Setup and Retraction Demonstration DESCRIPTION: This snippet demonstrates setting up a Go workspace and retrieving a module with a retracted version. It involves copying a go.mod file, unsetting the GOWORK environment variable, fetching a specific module version, and observing 'retracted' messages in the standard error. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/mod_get_workspace_incomplete.txt#_snippet_12 LANGUAGE: bash CODE: ``` cp go.mod.orig go.mod env GOWORK= go get example.com/retract@v1.0.0-good stderr 'retracted' ``` -------------------------------- TITLE: Go Get: Wildcard Fetch with Version Mismatch DESCRIPTION: This example demonstrates the behavior of 'go get' when a wildcard pattern matches packages in a module but not at the requested version. It shows how the command fails and provides an error message indicating the version mismatch for the module. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/mod_get_split.txt#_snippet_2 LANGUAGE: bash CODE: ``` ! go get example.net/split/nested/... stderr '^go: example.net/split/nested/\.\.\.@v0.1.0 matches packages in example.net/split@v0.2.0 but not example.net/split@v0.1.0: specify a different version for module example.net/split$' cmp go.mod go.mod.orig ``` -------------------------------- TITLE: Go Source Code (Example A) DESCRIPTION: A Go source file for package 'a', demonstrating function calls to packages 'p' and 'q'. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/work_sync.txt#_snippet_3 LANGUAGE: go CODE: ``` package a import ( "example.com/p" "example.com/q" ) func Foo() { p.P() q.Q() } ``` -------------------------------- TITLE: Setting up Go Environment Variables and Directories DESCRIPTION: This snippet configures the Go environment by setting crucial environment variables like NEWGOROOT and TOOLDIR, and creating necessary directories. It utilizes symlinks to establish the GOROOT structure, pointing to the existing Go installation's source and binary directories. This setup is foundational for building and running Go programs. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/tool_build_as_needed.txt#_snippet_0 LANGUAGE: bash CODE: ``` env NEWGOROOT=$WORK${/}goroot env TOOLDIR=$GOROOT/pkg/tool/${GOOS}_${GOARCH} # Use ${/} in paths we'll check for in stdout below, so they contain '\' on Windows env NEWTOOLDIR=$NEWGOROOT${/}pkg${/}tool${/}${GOOS}_${GOARCH} mkdir $NEWGOROOT $NEWGOROOT/bin $NEWTOOLDIR [symlink] symlink $NEWGOROOT/src -> $GOROOT/src [symlink] symlink $NEWGOROOT/pkg/include -> $GOROOT/pkg/include [symlink] symlink $NEWGOROOT/bin/go -> $GOROOT/bin/go [symlink] symlink $NEWTOOLDIR/compile$GOEXE -> $TOOLDIR/compile$GOEXE [symlink] symlink $NEWTOOLDIR/cgo$GOEXE -> $TOOLDIR/cgo$GOEXE [symlink] symlink $NEWTOOLDIR/link$GOEXE -> $TOOLDIR/link$GOEXE [symlink] symlink $NEWTOOLDIR/asm$GOEXE -> $TOOLDIR/asm$GOEXE [symlink] symlink $NEWTOOLDIR/pack$GOEXE -> $TOOLDIR/pack$GOEXE env GOROOT=$NEWGOROOT env TOOLDIR=$NEWTOOLDIR ``` -------------------------------- TITLE: Go testing package MainStart function DESCRIPTION: The MainStart function in the 'testing' package is used to start tests, benchmarks, and examples. It accepts a function for test dependencies, and slices for tests, benchmarks, and examples. SOURCE: https://github.com/golang/go/blob/master/api/except.txt#_snippet_48 LANGUAGE: go CODE: ``` pkg testing, func MainStart(func(string, string) (bool, error), []InternalTest, []InternalBenchmark, []InternalExample) *M ``` LANGUAGE: go CODE: ``` pkg testing, func MainStart(testDeps, []InternalTest, []InternalBenchmark, []InternalExample) *M ``` -------------------------------- TITLE: Main Execution Logic (run_go.go) DESCRIPTION: The `run_go.go` file contains the main logic for setting up and running a Go command. It parses arguments for GOPATH and directory, sets up the environment for the child process, and executes `hello.go`. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/vendor_gopath_issue11409.txt#_snippet_1 LANGUAGE: go CODE: ``` package main import ( "fmt" "os" "os/exec" "path/filepath" "strings" ) func changeVolume(s string, f func(s string) string) string { vol := filepath.VolumeName(s) return f(vol) + s[len(vol):] } func main() { gopath := changeVolume(os.Args[1], strings.ToLower) dir := changeVolume(os.Args[2], strings.ToUpper) cmd := exec.Command("go", "run", "hello.go") cmd.Dir = dir cmd.Env = append(os.Environ(), "GOPATH="+gopath) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } ``` -------------------------------- TITLE: Install Specific Tool Version with go get -tool DESCRIPTION: Installs a specific version of a tool using 'go get -tool'. It modifies the go.mod file to include the tool and its version. This is useful for pinning dependencies. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/mod_get_tool.txt#_snippet_0 LANGUAGE: bash CODE: ``` go get -tool example.com/tools/cmd/hello@v1.0.0 cmp go.mod go.mod.want ``` -------------------------------- TITLE: Error Handling for 'go get -tool all' DESCRIPTION: Shows the error message when 'go get -tool all' is used, as this command is not supported for installing all tools. It highlights a limitation in managing tools collectively with 'all'. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/mod_get_tool.txt#_snippet_5 LANGUAGE: bash CODE: ``` ! go get -tool all stderr 'go get -tool does not work with "all"' ``` -------------------------------- TITLE: Go testing MainStart Function DESCRIPTION: Shows how to initiate the Go testing framework, including dependency setup and test/benchmark/example execution. SOURCE: https://github.com/golang/go/blob/master/api/go1.8.txt#_snippet_90 LANGUAGE: go CODE: ``` func MainStart(testDeps, []InternalTest, []InternalBenchmark, []InternalExample) *M ``` -------------------------------- TITLE: Populate go.sum and List Import Path (GO=off) DESCRIPTION: Demonstrates populating the go.sum file using 'go get' and then listing the import path of the 'math' package with GO111MODULE set to off. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/mod_list_dir.txt#_snippet_0 LANGUAGE: go CODE: ``` env GO111MODULE=off go get go list -f '{{.ImportPath}}' $GOROOT/src/math stdout ^math$ ``` -------------------------------- TITLE: Build and Run Go Program on Windows DESCRIPTION: This snippet details the commands to build and execute a Go program (`run_go.go`) on a Windows environment. It sets up the necessary environment variables and executes the compiled program, which in turn runs another Go program (`hello.go`) from a vendored directory. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/vendor_gopath_issue11409.txt#_snippet_0 LANGUAGE: bash CODE: ``` #!/bin/bash GOOS=windows go build run_go.go exec ./run_go$GOEXE $GOPATH $GOPATH/src/vend/hello stdout 'hello, world' ``` -------------------------------- TITLE: Go Source Code (Example B) DESCRIPTION: A Go source file for package 'b', demonstrating function calls to packages 'p' and 'q'. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/work_sync.txt#_snippet_6 LANGUAGE: go CODE: ``` package b import ( "example.com/p" "example.com/q" ) func Foo() { p.P() q.Q() } ``` -------------------------------- TITLE: Build and Execute a Simple Go Program DESCRIPTION: This snippet shows the basic commands to build and execute a Go program. It compiles the 'hello.go' file and then runs the resulting binary. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/build_static.txt#_snippet_0 LANGUAGE: bash CODE: ``` go build exec ./hello ``` -------------------------------- TITLE: Get Install Path for Standard Command DESCRIPTION: Retrieves the installation target path for a standard Go command (cmd/pack) using the `go list` command with a custom format string. The output shows the expected directory structure, including GOOS and GOARCH. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/install_cross_gobin.txt#_snippet_3 LANGUAGE: shell CODE: ``` go list -f '{{.Target}}' cmd/pack stdout ${GOROOT}[/\\]pkg[[/\\]]tool[[/\\]]${GOOS}_${GOARCH}[[/\\]]pack$ ``` -------------------------------- TITLE: Go Get: Wildcard Update for Modules and Packages DESCRIPTION: This snippet demonstrates how a wildcard pattern in 'go get' can update both modules and their packages to a specified version. It shows fetching all packages under 'example.net' with a specific version and then fetching without a version to get the latest. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/mod_get_split.txt#_snippet_5 LANGUAGE: bash CODE: ``` cp go.mod.orig go.mod go get example.net/split/nested@v0.0.0 go get example.net/... ``` LANGUAGE: bash CODE: ``` go list -m all stdout '^example.net/split v0.3.0 ' stdout '^example.net/split/nested v0.2.0 ' ``` -------------------------------- TITLE: Module Q Test Implementation DESCRIPTION: The 'q_test.go' file for package 'q' imports 'example.com/s'. This demonstrates dependency management within test files. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/mod_all.txt#_snippet_32 LANGUAGE: go CODE: ``` package q_test import _ "example.com/s" ``` -------------------------------- TITLE: Get Specific Go Module Version DESCRIPTION: Retrieves and installs a specific version of a module. This command also updates the go.mod file. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/version_replace.txt#_snippet_1 LANGUAGE: go CODE: ``` go get example.com/printversion@v0.1.0 ``` -------------------------------- TITLE: Build Go Project and Manage Cache DESCRIPTION: This snippet demonstrates building a Go project, ensuring the runtime/cgo package is cached, and then executing the build with verbose output. It highlights the importance of the build cache for dependencies. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/build_dash_x.txt#_snippet_0 LANGUAGE: shell CODE: ``` env GOCACHE=$WORK/tmp/cache go build runtime/cgo go build -x -o main ./... ``` -------------------------------- TITLE: Use Wildcards with go get -tool DESCRIPTION: Installs tools from a directory using a wildcard pattern like './cmd/...'. This allows for managing multiple tools within a package structure. Attempting to use '@none' with wildcards results in an error. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/mod_get_tool.txt#_snippet_4 LANGUAGE: bash CODE: ``` go get -tool ./cmd/... cmp go.mod go.mod.wildcard ! go get -tool ./cmd/...@none stderr 'can''t request explicit version "none" of path "./cmd/..." in main module' ``` -------------------------------- TITLE: Basic Go Program DESCRIPTION: A minimal Go program that defines the main package and an empty main function. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/install_cross_gobin.txt#_snippet_4 LANGUAGE: go CODE: ``` package main func main() {} ``` -------------------------------- TITLE: Golang Project Setup with Vendor Directory DESCRIPTION: This snippet demonstrates the creation of a vendor directory, setting up symlinks for module paths, and copying Go source files. It configures the environment variables for GOPATH and then executes `go list` to show project dependencies. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/list_symlink_vendor_issue15201.txt#_snippet_0 LANGUAGE: shell CODE: ``` env GO111MODULE=off mkdir $WORK/tmp/gopath/src/x/y/_vendor/src/x symlink $WORK/tmp/gopath/src/x/y/_vendor/src/x/y -> ../../../ mkdir $WORK/tmp/gopath/src/x/y/_vendor/src/x/y/w cp w.go $WORK/tmp/gopath/src/x/y/w/w.go symlink $WORK/tmp/gopath/src/x/y/w/vendor -> ../_vendor/src mkdir $WORK/tmp/gopath/src/x/y/_vendor/src/x/y/z cp z.go $WORK/tmp/gopath/src/x/y/z/z.go env GOPATH=$WORK/tmp/gopath/src/x/y/_vendor${:}$WORK/tmp/gopath cd $WORK/tmp/gopath/src go list ./... ``` -------------------------------- TITLE: Building a Go executable and placing it directly in a directory DESCRIPTION: Creates a 'bin' directory, builds 'x.go' into it as 'bin/x', verifies its execution, and then removes the 'bin' directory. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/build_output.txt#_snippet_5 LANGUAGE: bash CODE: ``` ! exists bin mkdir bin go build -o bin x.go exists -exec bin/x$GOEXE rm bin ``` -------------------------------- TITLE: Go Get: Update Package in Build List DESCRIPTION: This example shows how 'go get' updates an existing package in the build list when a new version is specified. It demonstrates fetching a specific patch version of a nested package and verifies the module list afterwards. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/mod_get_split.txt#_snippet_0 LANGUAGE: bash CODE: ``` cp go.mod go.mod.orig go get example.net/split/nested@patch go list -m all stdout '^example.net/split v0.2.1 ' ! stdout '^example.net/split/nested' ``` LANGUAGE: bash CODE: ``` cp go.mod.orig go.mod go get example.net/split/nested/... ``` -------------------------------- TITLE: Golang Main Application (main.go) DESCRIPTION: A simple Golang program that imports the 'C' package (likely for cgo) and prints 'hello\n' to the console. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/build_dash_x.txt#_snippet_3 LANGUAGE: go CODE: ``` package main import "C" func main() { print("hello\n") } ``` -------------------------------- TITLE: Go For Clause Variable Scoping (Go 1.22+) DESCRIPTION: Demonstrates the variable scoping behavior in Go 'for' loops starting from version 1.22, where each iteration gets its own distinct variable. This example highlights the output difference compared to pre-1.22 versions. SOURCE: https://github.com/golang/go/blob/master/doc/go_spec.html#_snippet_170 LANGUAGE: Go CODE: ``` var prints []func() for i := 0; i < 5; i++ { prints = append(prints, func() { println(i) }) i++ } for _, p := range prints { p() } ``` -------------------------------- TITLE: Preview Local Website with Release Notes DESCRIPTION: Command to run a local instance of the Go website to preview `next` release notes content. It requires the `golang.org/x/website` module and specifies the Go root directory. SOURCE: https://github.com/golang/go/blob/master/doc/README.md#_snippet_0 LANGUAGE: bash CODE: ``` go run golang.org/x/website/cmd/golangorg@latest -goroot=.. ``` -------------------------------- TITLE: Wildcard Package Installation with Go DESCRIPTION: Demonstrates installing packages using wildcards. It ensures that wildcards only match main packages and handles scenarios with non-main packages or no matching packages. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/mod_install_pkg_version.txt#_snippet_11 LANGUAGE: bash CODE: ``` # Wildcards should match only main packages. This module has a non-main package # with an error, so we'll know if that gets built. mkdir tmp cd tmp go mod init m go get example.com/cmd@v1.0.0 ! go build example.com/cmd/... stderr 'err[/\]err.go:3:9: undefined: DoesNotCompile( .*)?$ cd .. go install example.com/cmd/...@v1.0.0 exists $GOPATH/bin/a$GOEXE exists $GOPATH/bin/b$GOEXE rm $GOPATH/bin # If a wildcard matches no packages, we should see a warning. ! go install example.com/cmd/nomatch...@v1.0.0 stderr '^go: example.com/cmd/nomatch\.\.\.@v1.0.0: module example.com/cmd@v1.0.0 found, but does not contain packages matching example.com/cmd/nomatch\.\.\.$' go install example.com/cmd/a@v1.0.0 example.com/cmd/nomatch...@v1.0.0 stderr '^go: warning: "example.com/cmd/nomatch\.\.\." matched no packages$' # If a wildcard matches only non-main packages, we should see a different warning. go install example.com/cmd/err...@v1.0.0 stderr '^go: warning: "example.com/cmd/err\.\.\." matched only non-main packages$' ``` -------------------------------- TITLE: Example Module 'q' (v1.1.0) Go Module Definition DESCRIPTION: The go.mod file for version 1.1.0 of module 'q'. It declares dependencies on 'example.com/w' and 'example.com/z', showcasing multiple direct dependencies in a vendored setup. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/work_vendor_prune_all.txt#_snippet_14 LANGUAGE: go CODE: ``` module example.com/q require example.com/w v1.0.0 require example.com/z v1.1.0 go 1.18 ``` -------------------------------- TITLE: Go Get Package Path Examples DESCRIPTION: Illustrates `go get` behavior with package paths, including those with `.go` suffixes and version specifiers. Arguments are treated as packages or patterns with versions, not source files. It shows successful `go get` operations with or without versions specified. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/mod_get_trailing_slash.txt#_snippet_1 LANGUAGE: bash CODE: ``` go get example.com/dotgo.go ``` LANGUAGE: bash CODE: ``` go get example.com/dotgo.go/ ``` LANGUAGE: bash CODE: ``` go get example.com/dotgo.go@v1.0.0 ``` LANGUAGE: bash CODE: ``` go get example.com/dotgo.go/@v1.0.0 ``` -------------------------------- TITLE: List All Module Dependencies DESCRIPTION: Lists all direct and indirect module requirements for the current project. This command is useful for verifying the current state of dependencies after modifications. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/mod_get_changes.txt#_snippet_3 LANGUAGE: bash CODE: ``` go list -m all ``` -------------------------------- TITLE: Install Directory Package (GO111MODULE=on) DESCRIPTION: Demonstrates installing a package using a directory path when GO111MODULE is enabled. It includes steps for setting up a temporary module and handling read-only mode. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/mod_install_pkg_version.txt#_snippet_5 LANGUAGE: bash CODE: ``` env GO111MODULE=on go mod download rsc.io/fortune@v1.0.0 ! go install $GOPATH/pkg/mod/rsc.io/fortune@v1.0.0 stderr '^go: go.mod file not found in current directory or any parent directory; see ' go help modules''$' ' ! go install ../pkg/mod/rsc.io/fortune@v1.0.0 stderr '^go: go.mod file not found in current directory or any parent directory; see ' go help modules''$' ' mkdir tmp cd tmp go mod init tmp go mod edit -require=rsc.io/fortune@v1.0.0 ! go install -mod=readonly $GOPATH/pkg/mod/rsc.io/fortune@v1.0.0 stderr '^missing go.sum entry for module providing package rsc.io/fortune; to add: go mod download rsc.io/fortune$' ! go install -mod=readonly ../../pkg/mod/rsc.io/fortune@v1.0.0 stderr '^missing go.sum entry for module providing package rsc.io/fortune; to add: go mod download rsc.io/fortune$' go get rsc.io/fortune@v1.0.0 go install -mod=readonly $GOPATH/pkg/mod/rsc.io/fortune@v1.0.0 exists $GOPATH/bin/fortune$GOEXE cd .. rm tmp rm $GOPATH/bin env GO111MODULE=auto ``` -------------------------------- TITLE: Initialize Git Repository and Set Author DESCRIPTION: Sets up environment variables for Git author and committer information and initializes a new Git repository. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/vcstest/git/tagtests.txt#_snippet_0 LANGUAGE: shell CODE: ``` env GIT_AUTHOR_NAME='Jay Conrod' env GIT_AUTHOR_EMAIL='jayconrod@google.com' env GIT_COMMITTER_NAME=$GIT_AUTHOR_NAME env GIT_COMMITTER_EMAIL=$GIT_AUTHOR_EMAIL git init ``` -------------------------------- TITLE: Go Module File Example DESCRIPTION: This is an example content of a go.mod file, specifying the module path and the required Go version. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/work_get_toolchain.txt#_snippet_1 LANGUAGE: go.mod CODE: ``` module m go 1.1 ``` -------------------------------- TITLE: Get with Vendor Flag (Error) DESCRIPTION: Attempts to use the '-mod=vendor' flag with the 'go get' command. This flag is not supported by 'go get' and will result in an error. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/mod_getmode_vendor.txt#_snippet_4 LANGUAGE: bash CODE: ``` ! go get -mod=vendor -u stderr 'flag provided but not defined: -mod' ``` -------------------------------- TITLE: Module Q Implementation DESCRIPTION: The 'q.go' file defines the 'q' package and imports 'example.com/r'. This shows a direct dependency relationship. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/mod_all.txt#_snippet_31 LANGUAGE: go CODE: ``` package q import _ "example.com/r" ``` -------------------------------- TITLE: Cross-Compile and Install (Implicit GOBIN) DESCRIPTION: Cross-compiles and installs a Go command for a specific architecture (386) and operating system (linux). Uses the implicit GOBIN setting, which defaults to $GOPATH/bin. It demonstrates checking for the existence of the installed binary in a subdirectory structure reflecting the OS and architecture. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/install_cross_gobin.txt#_snippet_1 LANGUAGE: shell CODE: ``` env GOARCH=386 [GOARCH:386] env GOARCH=amd64 env GOOS=linux go install mycmd exists $GOPATH/bin/linux_$GOARCH/mycmd ``` -------------------------------- TITLE: Go Module Initialization: 'gopkg.in' Domain Rules DESCRIPTION: Illustrates Go module initialization for the 'gopkg.in' domain, highlighting the mandatory '.vN' suffix requirement for all module paths starting with 'gopkg.in/'. This ensures proper versioning for packages hosted on this domain. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/mod_init_invalid_major.txt#_snippet_2 LANGUAGE: bash CODE: ``` ! go mod init gopkg.in/pkg stderr '(?s)^go: invalid module path "gopkg.in/pkg": module paths beginning with gopkg.in/ must always have a major version suffix in the form of .vN(.*)go mod init gopkg.in/pkg.v1$' ``` LANGUAGE: bash CODE: ``` ! go mod init gopkg.in/user/pkg stderr '(?s)^go: invalid module path "gopkg.in/user/pkg": module paths beginning with gopkg.in/ must always have a major version suffix in the form of .vN(.*)go mod init gopkg.in/user/pkg.v1$' ``` LANGUAGE: bash CODE: ``` ! go mod init gopkg.in/user/pkg/v0 stderr '(?s)^go: invalid module path "gopkg.in/user/pkg/v0": module paths beginning with gopkg.in/ must always have a major version suffix in the form of .vN(.*)go mod init gopkg.in/user/pkg.v1$' ``` LANGUAGE: bash CODE: ``` ! go mod init gopkg.in/user/pkg/v1 stderr '(?s)^go: invalid module path "gopkg.in/user/pkg/v1": module paths beginning with gopkg.in/ must always have a major version suffix in the form of .vN(.*)go mod init gopkg.in/user/pkg.v1$' ``` LANGUAGE: bash CODE: ``` ! go mod init gopkg.in/user/pkg/v2 stderr '(?s)^go: invalid module path "gopkg.in/user/pkg/v2": module paths beginning with gopkg.in/ must always have a major version suffix in the form of .vN(.*)go mod init gopkg.in/user/pkg.v2$' ``` LANGUAGE: bash CODE: ``` ! go mod init gopkg.in/user/pkg.v stderr '(?s)^go: invalid module path "gopkg.in/user/pkg.v": module paths beginning with gopkg.in/ must always have a major version suffix in the form of .vN(.*)go mod init gopkg.in/user/pkg.v1$' ``` LANGUAGE: bash CODE: ``` ! go mod init gopkg.in/user/pkg.v0.1 stderr '(?s)^go: invalid module path "gopkg.in/user/pkg.v0.1": module paths beginning with gopkg.in/ must always have a major version suffix in the form of .vN(.*)go mod init gopkg.in/user/pkg.v1$' ``` LANGUAGE: bash CODE: ``` ! go mod init gopkg.in/user/pkg.v.1 stderr '(?s)^go: invalid module path "gopkg.in/user/pkg.v.1": module paths beginning with gopkg.in/ must always have a major version suffix in the form of .vN(.*)go mod init gopkg.in/user/pkg.v1$' ``` LANGUAGE: bash CODE: ``` ! go mod init gopkg.in/user/pkg.v01 stderr '(?s)^go: invalid module path "gopkg.in/user/pkg.v01": module paths beginning with gopkg.in/ must always have a major version suffix in the form of .vN(.*)go mod init gopkg.in/user/pkg.v1$' ``` LANGUAGE: bash CODE: ``` ! go mod init gopkg.in/user/pkg.v.2.3 stderr '(?s)^go: invalid module path "gopkg.in/user/pkg.v.2.3": module paths beginning with gopkg.in/ must always have a major version suffix in the form of .vN(.*)go mod init gopkg.in/user/pkg.v2$' ``` -------------------------------- TITLE: Go Get Default Behavior DESCRIPTION: Shows that the default 'go get' command behaves like 'go get @upgrade', maintaining the current pseudoverison and not downgrading. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/mod_get_upgrade_pseudo.txt#_snippet_3 LANGUAGE: shell CODE: ``` go get example.com/pseudoupgrade go list -m all stdout '^example.com/pseudoupgrade v0.1.1-0.20190429073117-b5426c86b553$' ``` -------------------------------- TITLE: Run Golang Application DESCRIPTION: Command to set the GO111MODULE environment variable, change directory to the application's vendored path, and execute the main Go program. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/run_vendor.txt#_snippet_0 LANGUAGE: shell CODE: ``` env GO111MODULE=off cd vend/hello go run hello.go stdout 'hello, world' ``` -------------------------------- TITLE: Go Module Initialization Example DESCRIPTION: Shows the `go.mod` file content for different modules, including requirements and module definitions. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/mod_tidy.txt#_snippet_4 LANGUAGE: go CODE: ``` module w ``` LANGUAGE: go CODE: ``` module x require w.1 v1.1.0 require z.1 v1.1.0 ``` LANGUAGE: go CODE: ``` module y require z.1 v1.2.0 ``` LANGUAGE: go CODE: ``` module z ``` LANGUAGE: go CODE: ``` module triv ``` -------------------------------- TITLE: Get Non-Excluded Go Module Version DESCRIPTION: Shows successfully getting a module version that is not excluded. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/mod_query_exclude.txt#_snippet_4 LANGUAGE: bash CODE: ``` env GO111MODULE=on # get non-excluded version cp go.exclude.mod.orig go.exclude.mod go get -modfile=go.exclude.mod rsc.io/quote@v1.5.1 ``` -------------------------------- TITLE: Go Program: Hello World DESCRIPTION: A simple Go program that prints 'hello!' to the console. This is the main entry point for the executable. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/clean_binary.txt#_snippet_6 LANGUAGE: go CODE: ``` package main import "fmt" func main() { fmt.Println("hello!") } ``` -------------------------------- TITLE: Go: Get incomplete module with work query DESCRIPTION: Tests 'go get' with an incomplete module using a 'work' query. It removes go.sum, runs 'go get work', and then compares the go.mod and go.sum files. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/mod_get_workspace_incomplete.txt#_snippet_2 LANGUAGE: bash CODE: ``` cp go.mod.orig go.mod rm go.sum go get work cmp go.mod go.mod.want cmp go.sum go.sum.want ``` -------------------------------- TITLE: Basic Git Workflow: Init, Add, Commit, Branch, Tag DESCRIPTION: Demonstrates a common Git workflow: initializing a repository, adding files, committing changes, renaming the main branch, and creating a tag. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/vcstest/git/issue47650.txt#_snippet_1 LANGUAGE: bash CODE: ``` git init git add cmd git commit -m 'add cmd/issue47650' git branch -m main git tag v0.1.0 git add go.mod git commit -m 'add go.mod' ``` -------------------------------- TITLE: Go: Get incomplete module with path query DESCRIPTION: Tests 'go get' with an incomplete module using a path query that can be resolved (e.g., 'rsc.io/quote'). It removes go.sum, runs 'go get rsc.io/quote', and compares the go.mod and go.sum files. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/mod_get_workspace_incomplete.txt#_snippet_3 LANGUAGE: bash CODE: ``` cp go.mod.orig go.mod rm go.sum go get rsc.io/quote cmp go.mod go.mod.want.path_query cmp go.sum go.sum.want ``` -------------------------------- TITLE: Run Tests and Benchmarks with MainStart (Go Testing) DESCRIPTION: The `MainStart` function from the `testing` package is used to initiate the execution of tests, benchmarks, and fuzz targets within a Go program. It accepts slices of test dependencies, internal tests, benchmarks, fuzz targets, and examples. SOURCE: https://github.com/golang/go/blob/master/api/go1.18.txt#_snippet_49 LANGUAGE: go CODE: ``` func MainStart(testDeps, []InternalTest, []InternalBenchmark, []InternalFuzzTarget, []InternalExample) *M ``` -------------------------------- TITLE: Go: Get incomplete module with wildcard query DESCRIPTION: Tests 'go get' with an incomplete module using a wildcard query ('./...'). It removes go.sum, runs 'go get ./...', and then compares the go.mod and go.sum files. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/mod_get_workspace_incomplete.txt#_snippet_1 LANGUAGE: bash CODE: ``` cp go.mod.orig go.mod rm go.sum go get ./... cmp go.mod go.mod.want cmp go.sum go.sum.want ``` -------------------------------- TITLE: Configure Git Author and Initial Commit DESCRIPTION: Sets environment variables for Git author and committer information, initializes a Git repository, adds Go module and source files, and creates an initial commit. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/vcstest/git/v3pkg.txt#_snippet_0 LANGUAGE: shell CODE: ``` env GIT_AUTHOR_NAME='Bryan C. Mills' env GIT_AUTHOR_EMAIL='bcmills@google.com' env GIT_COMMITTER_NAME=$GIT_AUTHOR_NAME env GIT_COMMITTER_EMAIL=$GIT_AUTHOR_AUTHOR_EMAIL git init env GIT_AUTHOR_DATE=2019-07-15T13:59:34-04:00 git add go.mod v3pkg.go git commit -a -m 'all: add go.mod with v3 path' ``` -------------------------------- TITLE: Go: Get incomplete module with local query DESCRIPTION: Tests 'go get' with an incomplete module using a local query. It copies the original go.mod, runs 'go get', and then compares the resulting go.mod and go.sum files with their expected versions. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/mod_get_workspace_incomplete.txt#_snippet_0 LANGUAGE: bash CODE: ``` cp go.mod.orig go.mod go get cmp go.mod go.mod.want cmp go.sum go.sum.want ``` -------------------------------- TITLE: Go Module Configuration (Example A) DESCRIPTION: Specifies the module path, Go version, and dependencies for module 'a'. Includes 'require' for direct dependencies and 'replace' for local module path overrides. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/work_sync.txt#_snippet_1 LANGUAGE: go CODE: ``` go 1.18 module example.com/a require ( example.com/p v1.0.0 example.com/q v1.1.0 example.com/r v1.0.0 ) replace ( example.com/p => ../p example.com/q => ../q example.com/r => ../r ) ``` -------------------------------- TITLE: Go Get: Update Module and Nested Packages DESCRIPTION: This example illustrates updating a module to a specific version and also updating nested packages within that module. It shows fetching a module and its nested packages with a shared version, and then verifying the changes in the module list. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/mod_get_split.txt#_snippet_4 LANGUAGE: bash CODE: ``` cp go.mod.orig go.mod go get example.net/split@v0.3.0 example.net/split/nested@v0.1.0 go list -m all stdout '^example.net/split v0.3.0 ' stdout '^example.net/split/nested v0.1.0 ' ``` -------------------------------- TITLE: Package 'main' Implementation DESCRIPTION: The main package includes functions 'MFunc' and 'M2Func', along with an init function and the primary 'main' function. It demonstrates usage of packages 'a' and 'b' and prints results to the console. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/cover_coverpkg_with_init.txt#_snippet_8 LANGUAGE: go CODE: ``` package main import ( "M/a" "M/b" ) func MFunc() string { return "42" } func M2Func() int { return a.AFunc() + b.BFunc() } func init() { println("package 'main' init") } func main() { println(a.AFunc() + b.BFunc()) } ``` -------------------------------- TITLE: Go: Get workspace module with unresolvable path query DESCRIPTION: Tests 'go get' with a path query to a workspace module that cannot be resolved. It checks that an error is returned indicating the module was not found. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/mod_get_workspace_incomplete.txt#_snippet_4 LANGUAGE: bash CODE: ``` cp go.mod.orig go.mod rm go.sum ! go get example.com/n stderr 'module example.com@upgrade found \(v1.0.0\), but does not contain package example.com/n' ``` -------------------------------- TITLE: Execute and Verify Go Application DESCRIPTION: This section details the execution of the compiled Go program and verification of its output. It includes steps to copy output and error streams to files, execute a test script, and compare the actual output with a reference file. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/build_dash_x.txt#_snippet_1 LANGUAGE: shell CODE: ``` cp stderr commands.txt cat header.txt commands.txt cp stdout test.sh exec ./main cmp stderr hello.txt rm ./main exec /usr/bin/env bash -x test.sh exec ./main cmp stderr hello.txt ``` -------------------------------- TITLE: Remove Dependency with 'go get' DESCRIPTION: Removes a Go module dependency from the project. 'go get' outputs messages for the removed requirement and any affected explicit dependencies. Changes to indirect dependencies are not shown. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/mod_get_changes.txt#_snippet_1 LANGUAGE: bash CODE: ``` go get rsc.io/sampler@none ``` -------------------------------- TITLE: Go: Get incomplete module with all query DESCRIPTION: Tests 'go get' with an incomplete module using an 'all' query. It removes go.sum, runs 'go get all', and compares the go.mod and go.sum files, noting that 'all' may load a different graph. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/mod_get_workspace_incomplete.txt#_snippet_5 LANGUAGE: bash CODE: ``` cp go.mod.orig go.mod rm go.sum go get all cmp go.mod go.mod.want.all cmp go.sum go.sum.want.all ``` -------------------------------- TITLE: Go Example Code (example.go) DESCRIPTION: A simple Go package example that imports another module. It demonstrates package declaration and import statements. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/mod_doc_path.txt#_snippet_1 LANGUAGE: go CODE: ``` package example import _ "example.com/p" ``` -------------------------------- TITLE: Go Module Initialization: Valid Paths DESCRIPTION: Initializes a new Go module with a valid path. This is the standard way to start a new module. The command sets up the go.mod file. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/mod_init_invalid_major.txt#_snippet_0 LANGUAGE: bash CODE: ``` env GO111MODULE=on env GOFLAGS=-mod=mod ! go mod init example.com/user/repo/v2 stderr '(?s)^go: invalid module path "example.com/user/repo/v0": major version suffixes must be in the form of /vN and are only allowed for v2 or later(.*)go mod init example.com/user/repo/v2$' ``` -------------------------------- TITLE: Go Module Configuration (Package Q) DESCRIPTION: Defines the module path and Go version for the 'q' module. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/work_sync.txt#_snippet_9 LANGUAGE: go CODE: ``` go 1.18 module example.com/q ``` -------------------------------- TITLE: Example Module 'w' Test File DESCRIPTION: A test file for module 'w'. It includes an underscore import of 'example.com/x', indicating that the test relies on 'x' for its setup or side effects. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/work_vendor_prune_all.txt#_snippet_20 LANGUAGE: go CODE: ``` package w import _ "example.com/x" ``` -------------------------------- TITLE: Go Get: Wildcard with Empty Module Resolution DESCRIPTION: This snippet demonstrates how a wildcard can resolve to an empty module with the same prefix, even if it contains no packages. It shows fetching all 'example.net' packages with '@none', then fetching a specific nested package, and verifying the module list. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/mod_get_split.txt#_snippet_7 LANGUAGE: bash CODE: ``` go get example.net/... go get example.net/split/... go list -m all stdout '^example.net/split v0.1.0 ' ``` -------------------------------- TITLE: Go Main Package Example DESCRIPTION: A simple Go program that prints the string 'hello' to standard output. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/build_cache_trimpath.txt#_snippet_2 LANGUAGE: go CODE: ``` package main func main() { println("hello") } ``` -------------------------------- TITLE: Get Go Module Query with Exclusions DESCRIPTION: Illustrates getting module versions using a range specifier when an exclusion is present. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/mod_query_exclude.txt#_snippet_5 LANGUAGE: bash CODE: ``` env GO111MODULE=on # get query with excluded version cp go.exclude.mod.orig go.exclude.mod go get -modfile=go.exclude.mod rsc.io/quote@>=v1.5 go list -modfile=go.exclude.mod -m ...quote ``` -------------------------------- TITLE: Initialize Go Workspace DESCRIPTION: Initializes a new Go workspace with specified module directories. It creates a `go.work` file to manage the workspace. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/work.txt#_snippet_0 LANGUAGE: bash CODE: ``` go work init ./a ./b ``` -------------------------------- TITLE: Get Excluded Go Module Version DESCRIPTION: Demonstrates attempting to get a module version that is excluded, showing the expected error. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/mod_query_exclude.txt#_snippet_3 LANGUAGE: bash CODE: ``` env GO111MODULE=on # get excluded version cp go.exclude.mod go.exclude.mod.orig ! go get -modfile=go.exclude.mod rsc.io/quote@v1.5.0 ``` -------------------------------- TITLE: Initialize Go Workspace DESCRIPTION: Initializes a Go workspace with the specified Go version and includes local modules 'a' and 'b'. This command sets up the workspace configuration. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/work_sync_relevant_dependency.txt#_snippet_0 LANGUAGE: go CODE: ``` go 1.18 use ( ./a ./b ) ``` -------------------------------- TITLE: Go Get Default with Newer Pseudoverison DESCRIPTION: Illustrates that the default 'go get' command maintains the newer pseudoverison and does not downgrade. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/mod_get_upgrade_pseudo.txt#_snippet_8 LANGUAGE: shell CODE: ``` go get example.com/pseudoupgrade go list -m -u all stdout '^example.com/pseudoupgrade v0.0.0-20190430073000-30950c05d534$' ``` -------------------------------- TITLE: Go Get with Upgrade Keyword DESCRIPTION: Tests that 'go get @upgrade' respects the current pseudoverison and does not downgrade to a tagged version. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/mod_get_upgrade_pseudo.txt#_snippet_2 LANGUAGE: shell CODE: ``` go get example.com/pseudoupgrade@upgrade go list -m all stdout '^example.com/pseudoupgrade v0.1.1-0.20190429073117-b5426c86b553$' ``` -------------------------------- TITLE: List all packages with specific patterns in Go DESCRIPTION: Lists all packages, packages in the main module, and packages starting with a specific prefix, using the 'go list' command with custom formatting. It demonstrates how different patterns like 'all', '... example.com/m/...', './...', and './xyz...' affect the output. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/mod_patterns.txt#_snippet_0 LANGUAGE: bash CODE: ``` env GO111MODULE=on cd m go list -f '{{.ImportPath}}: {{.Match}}' all ... example.com/m/... ./... ./xyz... ``` -------------------------------- TITLE: Install mtime and sametime programs DESCRIPTION: Installs the 'mtime' and 'sametime' Go programs into the GOBIN directory. These programs are used later in the tests to get file modification times and compare timestamps. SOURCE: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/test_race_install_cgo.txt#_snippet_0 LANGUAGE: shell CODE: ``` env GOBIN=$WORK/bin go install m/mtime m/sametime ```