### Installing go-colorable Library in Go Source: https://github.com/voidint/g/blob/master/vendor/github.com/mattn/go-colorable/README.md This command demonstrates how to install the `go-colorable` library using the Go module system. Executing `go get github.com/mattn/go-colorable` downloads and installs the package, making it available for use in Go projects. ```shell $ go get github.com/mattn/go-colorable ``` -------------------------------- ### Installing gomonkey (below v2.1.0) - Go Source: https://github.com/voidint/g/blob/master/vendor/github.com/agiledragon/gomonkey/v2/README.md This command installs a specific version of the gomonkey library (below v2.1.0) using Go's module-aware 'go get' command. It fetches the specified version from the GitHub repository, ensuring compatibility with older project setups. ```Go $ go get github.com/agiledragon/gomonkey@v2.0.2 ``` -------------------------------- ### Installing the Match Go Package Source: https://github.com/voidint/g/blob/master/vendor/github.com/tidwall/match/README.md This command installs the 'Match' Go package using the `go get` utility. The `-u` flag ensures that the package is updated to the latest available version, fetching it from the specified GitHub repository. ```Shell go get -u github.com/tidwall/match ``` -------------------------------- ### Installing colorstring Go Library Source: https://github.com/voidint/g/blob/master/vendor/github.com/mitchellh/colorstring/README.md This command installs the `colorstring` Go library using the standard `go get` tool. It fetches the library from its GitHub repository and makes it available for use in Go projects. This is a prerequisite for using the library's functionalities. ```bash $ go get github.com/mitchellh/colorstring ``` -------------------------------- ### Installing gxz Command-Line Tool Source: https://github.com/voidint/g/blob/master/vendor/github.com/ulikunitz/xz/README.md This command installs the `gxz` command-line utility, which is part of the `github.com/ulikunitz/xz` Go package, by fetching and building it from the specified GitHub repository. ```Shell $ go get github.com/ulikunitz/xz/cmd/gxz ``` -------------------------------- ### Installing Pretty Go Package Source: https://github.com/voidint/g/blob/master/vendor/github.com/tidwall/pretty/README.md This command installs the 'Pretty' Go package using `go get`. The `-u` flag ensures that the package and its dependencies are updated to their latest versions. ```Shell $ go get -u github.com/tidwall/pretty ``` -------------------------------- ### Installing progressbar Go Library Source: https://github.com/voidint/g/blob/master/vendor/github.com/schollz/progressbar/v3/README.md This command installs the `progressbar` library for Go. It uses `go get` to fetch the latest version (`v3`) from GitHub and update it if already present. This is the first step to integrate the library into a Go project. ```Shell go get -u github.com/schollz/progressbar/v3 ``` -------------------------------- ### Installing gomonkey (v2.1.0 and above) - Go Source: https://github.com/voidint/g/blob/master/vendor/github.com/agiledragon/gomonkey/v2/README.md This command installs a specific version of the gomonkey library (v2.1.0 and above) using Go's module-aware 'go get' command, specifying the v2 module path. This is the recommended installation method for newer projects. ```Go $ go get github.com/agiledragon/gomonkey/v2@v2.11.0 ``` -------------------------------- ### Installing Blackfriday Command-Line Tool Source: https://github.com/voidint/g/blob/master/vendor/github.com/russross/blackfriday/v2/README.md This command installs the `blackfriday-tool` command-line utility, which provides a standalone program for processing Markdown files. Installing this tool also downloads and installs the Blackfriday library itself if it's not already present, placing the binary in `$GOPATH/bin`. ```Shell go get github.com/russross/blackfriday-tool ``` -------------------------------- ### Installing go-isatty Go Package Source: https://github.com/voidint/g/blob/master/vendor/github.com/mattn/go-isatty/README.md This command installs the `go-isatty` package into your Go workspace. It fetches the package source code from GitHub and makes it available for use in your Go projects. ```Shell $ go get github.com/mattn/go-isatty ``` -------------------------------- ### Installing Go 1.13beta1 via go get Command Source: https://github.com/voidint/g/blob/master/collector/official/testdata/golang_dl.html This command is used to install the go1.13beta1 unstable version of the Go language. It leverages the 'go get' utility, which requires an existing Go installation to fetch and install Go modules or tools from a specified path. ```Go go get golang.org/dl/go1.13beta1 ``` -------------------------------- ### Installing uritemplate Go Library Source: https://github.com/voidint/g/blob/master/vendor/github.com/yosida95/uritemplate/v3/README.rst This command installs the `uritemplate` Go library using `go get`. The `-u` flag ensures that the package and its dependencies are updated to their latest versions, making it ready for use in Go projects. ```Shell $ go get -u github.com/yosida95/uritemplate/v3 ``` -------------------------------- ### Installing the Xz Go Package Source: https://github.com/voidint/g/blob/master/vendor/github.com/xi2/xz/README.md This command downloads and installs the `xz` Go package from GitHub, making its native XZ decompression capabilities available for use in Go projects. ```Shell go get github.com/xi2/xz ``` -------------------------------- ### Installing uniseg Go Package Source: https://github.com/voidint/g/blob/master/vendor/github.com/rivo/uniseg/README.md This snippet provides the command to install the `uniseg` package for Go projects using the `go get` command. This command fetches the package and its dependencies, making it available for import in your Go applications. ```Bash go get github.com/rivo/uniseg ``` -------------------------------- ### Installing goquery Library in Go Source: https://github.com/voidint/g/blob/master/vendor/github.com/PuerkitoBio/goquery/README.md This command uses `go get` to download and install the `goquery` library into your Go workspace. It fetches the latest version of the library from its GitHub repository, making it available for use in your Go projects. ```Shell go get github.com/PuerkitoBio/goquery ``` -------------------------------- ### Installing Unstable Go Version (go1.13beta1) via go get Source: https://github.com/voidint/g/blob/master/version/testdata/golang_dl.html This command installs a specific unstable Go version, `go1.13beta1`, using the `go get` tool. It's a prerequisite for using this particular Go release and is intended for users who already have a standard Go installation. This version is unstable and should be used with caution. ```Shell go get golang.org/dl/go1.13beta1 ``` -------------------------------- ### Automated Installation of `g` for Linux/macOS Source: https://github.com/voidint/g/blob/master/README.md This snippet provides commands for automated installation of the `g` Go version manager on Linux and macOS. It first downloads and executes the `install.sh` script, then appends a check to `~/.bashrc` to unalias `g` if it exists, and finally sources the `g` environment file to enable the tool. It's recommended to clear existing `GOROOT` and `GOBIN` variables before running. ```shell # It is recommended to clear the `GOROOT`, `GOBIN`, and other environment variables before installation. $ curl -sSL https://raw.githubusercontent.com/voidint/g/master/install.sh | bash $ cat << 'EOF' >> ~/.bashrc # Check if the alias 'g' exists before trying to unalias it if [[ -n $(alias g 2>/dev/null) ]]; then unalias g fi EOF $ source "$HOME/.g/env" ``` -------------------------------- ### Installing Blackfriday v2 Go Module Source: https://github.com/voidint/g/blob/master/vendor/github.com/russross/blackfriday/v2/README.md This command installs the Blackfriday v2 Go module into the current development module. It resolves dependencies, downloads the package, and builds/installs it, making the library available for use in Go projects. ```Shell go get github.com/russross/blackfriday/v2 ``` -------------------------------- ### Configuring `g` Environment Variables for Linux/macOS Manual Installation Source: https://github.com/voidint/g/blob/master/README.md This snippet creates or overwrites the `~/.g/env` file, which defines essential environment variables for the `g` tool and Go installations. It sets `GOROOT` to the expected Go installation path, prepends `g`'s binary directory and `GOROOT/bin` to the system `PATH`, and configures `G_MIRROR` for Go downloads. This file is sourced by the shell to enable `g`. ```shell $ cat >~/.g/env <<'EOF' #!/bin/sh # g shell setup export GOROOT="${HOME}/.g/go" export PATH="${HOME}/.g/bin:${GOROOT}/bin:$PATH" export G_MIRROR=https://golang.google.cn/dl/ EOF ``` -------------------------------- ### Installing pgzip and Dependencies - Go Source: https://github.com/voidint/g/blob/master/vendor/github.com/klauspost/pgzip/README.md This snippet provides the commands to install the pgzip library and its required dependencies using the Go module system. It ensures that both pgzip and its underlying compression library are up-to-date for development. ```Go go get github.com/klauspost/pgzip/... go get -u github.com/klauspost/compress ``` -------------------------------- ### Automated Installation of `g` for Windows PowerShell Source: https://github.com/voidint/g/blob/master/README.md This command performs an automated installation of the `g` Go version manager on Windows using PowerShell. It downloads the `install.ps1` script from GitHub using `Invoke-WebRequest` (`iwr`) and then executes it using `Invoke-Expression` (`iex`), ensuring the `-useb` parameter is used for binary transfer. ```pwsh $ iwr https://raw.githubusercontent.com/voidint/g/master/install.ps1 -useb | iex ``` -------------------------------- ### Integrating `g` Environment Setup into Bash/Zsh Profile Source: https://github.com/voidint/g/blob/master/README.md This command appends a block to the user's `~/.bashrc` (or `~/.zshrc`) file. This block conditionally sources the `~/.g/env` file, which contains the `g` tool's environment variables. This ensures that `g` and its managed Go versions are correctly configured every time a new shell session starts. ```shell $ cat >>~/.bashrc <<'EOF' # g shell setup if [ -f "${HOME}/.g/env" ]; then . "${HOME}/.g/env" fi EOF ``` -------------------------------- ### Installing LZ4 Go Package Source: https://github.com/voidint/g/blob/master/vendor/github.com/pierrec/lz4/v4/README.md This command installs the `lz4` Go package, allowing its use in Go projects for LZ4 compression and decompression functionalities. ```Shell go get github.com/pierrec/lz4/v4 ``` -------------------------------- ### Installing concurrent-map Package via Go Get Source: https://github.com/voidint/g/blob/master/vendor/github.com/orcaman/concurrent-map/v2/README.md This command installs the `concurrent-map` package into your Go module cache, making it available for use in your Go projects. It fetches the specified version from GitHub. ```Bash go get "github.com/orcaman/concurrent-map/v2" ``` -------------------------------- ### Installing Unstable Go Version via go get Source: https://github.com/voidint/g/blob/master/collector/official/testdata/golang_dl_with_rc.html This command installs a specific unstable release candidate of the Go programming language (go1.13rc1) using the `go get` utility. After installation, users should use the `go1.13rc1` command instead of the standard `go` command to utilize this specific version. ```Shell go get golang.org/dl/go1.13rc1 ``` -------------------------------- ### Using the Installed Go 1.13beta1 Command Source: https://github.com/voidint/g/blob/master/collector/official/testdata/golang_dl.html After successfully installing the go1.13beta1 version, this snippet indicates how to invoke it. Users should substitute 'go1.13beta1' for the standard 'go' command when executing Go-related operations to ensure they are using this specific unstable release. ```Go go1.13beta1 ``` -------------------------------- ### Installing Unstable Go Version via go get Source: https://github.com/voidint/g/blob/master/version/testdata/golang_dl_with_rc.html This command installs a specific unstable release candidate of the Go language (go1.13rc1) using the `go get` tool. After installation, users should invoke `go1.13rc1` instead of the standard `go` command to utilize this particular version. This method is suitable for testing unstable releases. ```Shell go get golang.org/dl/go1.13rc1 ``` -------------------------------- ### Installing Go Compression Libraries Source: https://github.com/voidint/g/blob/master/vendor/github.com/dsnet/compress/README.md This command installs the `dsnet/compress` library and its dependencies using the Go module system. It fetches the latest version of the repository, making the compression packages available for use in Go projects. A Go version of 1.9 or higher is required for successful compilation. ```Go go get -u github.com/dsnet/compress ``` -------------------------------- ### Installing a Specific Go Version with g (Shell) Source: https://github.com/voidint/g/blob/master/README.md This command installs a specified version of Go. It downloads the Go package, verifies its checksum, and then sets it as the currently active Go version. The command requires a specific Go version number as an argument. ```shell $ g install 1.14.7 Downloading 100% [===============] (92/92 MB, 12 MB/s) Computing checksum with SHA256 Checksums matched Now using go1.20.5 ``` -------------------------------- ### Installing GJSON Go Package Source: https://github.com/voidint/g/blob/master/vendor/github.com/tidwall/gjson/README.md This command installs the GJSON Go package using the Go module system. It retrieves the library from GitHub, making it available for use in Go projects. ```sh go get -u github.com/tidwall/gjson ``` -------------------------------- ### Compressing and Decompressing Data with xz API in Go Source: https://github.com/voidint/g/blob/master/vendor/github.com/ulikunitz/xz/README.md This Go example demonstrates how to use the `github.com/ulikunitz/xz` package to compress a string into a `bytes.Buffer` using `xz.NewWriter` and then decompress it back to standard output using `xz.NewReader`. It includes error handling for each step of the compression and decompression process. ```Go package main import ( "bytes" "io" "log" "os" "github.com/ulikunitz/xz" ) func main() { const text = "The quick brown fox jumps over the lazy dog.\n" var buf bytes.Buffer // compress text w, err := xz.NewWriter(&buf) if err != nil { log.Fatalf("xz.NewWriter error %s", err) } if _, err := io.WriteString(w, text); err != nil { log.Fatalf("WriteString error %s", err) } if err := w.Close(); err != nil { log.Fatalf("w.Close error %s", err) } // decompress buffer and write output to stdout r, err := xz.NewReader(&buf) if err != nil { log.Fatalf("NewReader error %s", err) } if _, err = io.Copy(os.Stdout, r); err != nil { log.Fatalf("io.Copy error %s", err) } } ``` -------------------------------- ### Installing LZ4 Command Line Tool Source: https://github.com/voidint/g/blob/master/vendor/github.com/pierrec/lz4/v4/README.md This command installs the `lz4c` command-line interface tool, which can be used to compress and decompress LZ4 files directly from the terminal. ```Shell go install github.com/pierrec/lz4/v4/cmd/lz4c@latest ``` -------------------------------- ### Importing Blackfriday v2 Package in Go Source: https://github.com/voidint/g/blob/master/vendor/github.com/russross/blackfriday/v2/README.md This Go import statement makes the Blackfriday v2 package available within a Go source file. When used in conjunction with `go get` without parameters, it triggers the download and installation of the module if not already present. ```Go import "github.com/russross/blackfriday/v2" ``` -------------------------------- ### Basic GJSON Dot Notation and Wildcard Path Examples Source: https://github.com/voidint/g/blob/master/vendor/github.com/tidwall/gjson/README.md This snippet provides examples of basic GJSON path syntax, including dot notation for nested fields, array indexing, wildcard characters (`*`, `?`), and escaping special characters (`\.`). It also shows how to get array length (`#`) and extract multiple values from an array of objects. ```text "name.last" >> "Anderson" "age" >> 37 "children" >> ["Sara","Alex","Jack"] "children.#" >> 3 "children.1" >> "Alex" "child*.2" >> "Jack" "c?ildren.0" >> "Sara" "fav\.movie" >> "Deer Hunter" "friends.#.first" >> ["Dale","Roger","Jane"] "friends.1.last" >> "Craig" ``` -------------------------------- ### Querying Stable Go Versions with g (Shell) Source: https://github.com/voidint/g/blob/master/README.md This command queries and lists the currently available stable versions of Go that can be installed using the `g` tool. It provides a list of version numbers, allowing users to identify which stable releases are available for installation. ```shell $ g ls-remote stable 1.19.10 1.20.5 ``` -------------------------------- ### Listing Installed Go Versions with g (Shell) Source: https://github.com/voidint/g/blob/master/README.md This command lists all Go versions currently installed on the system using the `g` tool. It indicates the active Go version with an asterisk (`*`). ```shell $ g ls 1.19.10 * 1.20.5 ``` -------------------------------- ### Switching Between Installed Go Versions with g (Shell) Source: https://github.com/voidint/g/blob/master/README.md This command switches the currently active Go version to a specified installed version. It updates the environment to use the selected Go binary, confirming the change by displaying the new Go version and architecture. ```shell $ g use 1.19.10 go version go1.19.10 darwin/arm64 ``` -------------------------------- ### Installing the fatih/color Go Package Source: https://github.com/voidint/g/blob/master/vendor/github.com/fatih/color/README.md This snippet provides the command to install the 'fatih/color' package using Go's module management tool. It fetches the package and its dependencies, making it available for use in Go projects. ```Bash go get github.com/fatih/color ``` -------------------------------- ### Listing All Remote Go Versions with g (Shell) Source: https://github.com/voidint/g/blob/master/README.md This command lists all Go versions available for installation from remote repositories, including stable, release candidate (rc), and older versions. It provides a comprehensive list for users to choose from. ```shell $ g ls-remote 1 1.2.2 1.3 1.3.1 ... 1.19.10 1.20rc1 1.20rc2 1.20rc3 1.20 1.20.1 1.20.2 1.20.3 1.20.4 * 1.20.5 ``` -------------------------------- ### Installing WLog Go Module Source: https://github.com/voidint/g/blob/master/vendor/github.com/dixonwille/wlog/v3/README.md This command adds the WLog package to your Go module file, fetching the latest version of the library. It's the standard way to include external Go dependencies in a project. ```Bash go get github.com/dixonwille/wlog/v3@latest ``` -------------------------------- ### Installing the Google UUID Go Package Source: https://github.com/voidint/g/blob/master/vendor/github.com/google/uuid/README.md This command installs the `github.com/google/uuid` package into your Go module cache, making it available for use in your Go projects. It fetches the latest version of the package from its Git repository. ```Shell go get github.com/google/uuid ``` -------------------------------- ### Clearing Go Installation Cache with g (Shell) Source: https://github.com/voidint/g/blob/master/README.md This command clears the cached Go installation package files. It removes downloaded `.tar.gz` files, freeing up disk space that was used for previous Go installations. ```shell $ g clean Remove go1.18.10.darwin-arm64.tar.gz Remove go1.19.10.darwin-arm64.tar.gz Remove go1.20.5.darwin-arm64.tar.gz ``` -------------------------------- ### Formatting JSON with pretty.Pretty in Go Source: https://github.com/voidint/g/blob/master/vendor/github.com/tidwall/pretty/README.md This example demonstrates how to use the `pretty.Pretty` function in Go to format a compact JSON string into a human-readable, pretty-printed format. The input JSON is provided, followed by the Go code that performs the formatting, and then the expected pretty-printed output. ```JSON {"name": {"first":"Tom","last":"Anderson"}, "age":37, "children": ["Sara","Alex","Jack"], "fav.movie": "Deer Hunter", "friends": [ {"first": "Janet", "last": "Murphy", "age": 44} ]} ``` ```Go result = pretty.Pretty(example) ``` ```JSON { "name": { "first": "Tom", "last": "Anderson" }, "age": 37, "children": ["Sara", "Alex", "Jack"], "fav.movie": "Deer Hunter", "friends": [ { "first": "Janet", "last": "Murphy", "age": 44 } ] } ``` -------------------------------- ### Google Analytics Initialization and Custom Download Handling in JavaScript Source: https://github.com/voidint/g/blob/master/version/testdata/golang_dl_with_rc.html This JavaScript snippet initializes Google Analytics for page view tracking and implements a custom click handler for elements with the class 'download'. When a download link is clicked, it extracts the filename, constructs a new URL by appending the filename as a 'download' query parameter to '/doc/install' (or '/doc/install/source' for source files), and then redirects the browser to this new URL, preventing the default link behavior. This ensures downloads are routed through a specific installation documentation page. ```JavaScript (function (i, s, o, g, r, a, m) { i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () { (i[r].q = i[r].q || []).push(arguments) }, i[r].l = 1 * new Date(); a = s.createElement(o), m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m) })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga'); ga('create', 'UA-11222381-2', 'auto'); ga('send', 'pageview'); $(document).ready(function () { $('a.download').click(function (e) { var filename = $(this).text(); var child = $(this).find('.filename'); if (child.length > 0) { filename = child.text(); } var filenameRE = /^go1\\.\\d+(\\.\\d+)?([a-z0-9]+)?\\.([a-z0-9]+)(-[a-z0-9]+)?(-osx10\\.[68])?\\.([a-z.]+)$/; var m = filenameRE.exec(filename); if (!m) { return; } var dest = "/doc/install"; if (filename.indexOf(".src.") != -1) { dest += "/source"; } dest += "?download=" + filename; e.preventDefault(); e.stopPropagation(); window.location = dest; }); }); ``` -------------------------------- ### Using the Installed Unstable Go Version Command Source: https://github.com/voidint/g/blob/master/version/testdata/golang_dl.html After installing an unstable Go version like `go1.13beta1`, this snippet demonstrates how to invoke that specific version directly as a command. This replaces the standard `go` command for operations intended for that particular Go release, allowing for testing of new features. ```Shell go1.13beta1 ``` -------------------------------- ### Compressing and Uncompressing String with LZ4 in Go Source: https://github.com/voidint/g/blob/master/vendor/github.com/pierrec/lz4/v4/README.md This Go example demonstrates how to compress an input string using `lz4.NewWriter` and then uncompress it back using `lz4.NewReader` with `io.Pipe` for streaming data between the compressor and decompressor. ```Go // Compress and uncompress an input string. s := "hello world" r := strings.NewReader(s) // The pipe will uncompress the data from the writer. pr, pw := io.Pipe() zw := lz4.NewWriter(pw) zr := lz4.NewReader(pr) go func() { // Compress the input string. _, _ = io.Copy(zw, r) _ = zw.Close() // Make sure the writer is closed _ = pw.Close() // Terminate the pipe }() _, _ = io.Copy(os.Stdout, zr) // Output: // hello world ``` -------------------------------- ### Demonstrating String Distance Functions in Go Source: https://github.com/voidint/g/blob/master/vendor/github.com/xrash/smetrics/README.md This example showcases the usage of various string distance algorithms provided by the `smetrics` package, including Wagner-Fischer (Levenshtein), Ukkonen, Jaro, Jaro-Winkler, Soundex, and Hamming. It demonstrates how to call each function with different string inputs and parameters. ```Go package main import ( "github.com/xrash/smetrics" ) func main() { smetrics.WagnerFischer("POTATO", "POTATTO", 1, 1, 2) smetrics.WagnerFischer("MOUSE", "HOUSE", 2, 2, 4) smetrics.Ukkonen("POTATO", "POTATTO", 1, 1, 2) smetrics.Ukkonen("MOUSE", "HOUSE", 2, 2, 4) smetrics.Jaro("AL", "AL") smetrics.Jaro("MARTHA", "MARHTA") smetrics.JaroWinkler("AL", "AL", 0.7, 4) smetrics.JaroWinkler("MARTHA", "MARHTA", 0.7, 4) smetrics.Soundex("Euler") smetrics.Soundex("Ellery") smetrics.Hamming("aaa", "aaa") smetrics.Hamming("aaa", "aab") } ``` -------------------------------- ### Configuring Parallel Gzip Compression - Go Source: https://github.com/voidint/g/blob/master/vendor/github.com/klauspost/pgzip/README.md This example demonstrates how to initialize a pgzip.Writer and configure its concurrency settings for parallel compression. It sets a block size of 100KB and allows up to 10 blocks to be processed concurrently, optimizing performance for large data streams. ```Go var b bytes.Buffer w := gzip.NewWriter(&b) w.SetConcurrency(100000, 10) w.Write([]byte("hello, world\n")) w.Close() ``` -------------------------------- ### Basic Operations with concurrent-map in Go Source: https://github.com/voidint/g/blob/master/vendor/github.com/orcaman/concurrent-map/v2/README.md This example illustrates the fundamental operations of the `concurrent-map` package: creating a new map, setting a key-value pair, retrieving a value by key, and removing an item. It showcases how to use `cmap.New`, `m.Set`, `m.Get`, and `m.Remove`. ```Go // Create a new map. m := cmap.New[string]() // Sets item within map, sets "bar" under key "foo" m.Set("foo", "bar") // Retrieve item from map. bar, ok := m.Get("foo") // Removes item under key "foo" m.Remove("foo") ``` -------------------------------- ### Creating and Using WLog UI Instance in Go Source: https://github.com/voidint/g/blob/master/vendor/github.com/dixonwille/wlog/v3/README.md This Go code demonstrates how to initialize a wlog.UI instance, simulate user input using strings.NewReader, and apply various wrappers like AddPrefix and AddConcurrent. It then calls different UI methods (Ask, Error, Info, Output, Running, Success, Warn) to display messages with configured prefixes and concurrency. ```Go var ui wlog.UI reader := strings.NewReader("User Input\r\n") //Simulate user typing "User Input" then pressing [enter] when reading from os.Stdin ui = wlog.New(reader, os.Stdout, os.Stdout) ui = wlog.AddPrefix("", wlog.Cross, " ", "", "", "~", wlog.Check, "!", ui) ui = wlog.AddConcurrent(ui) ui.Ask("Ask question", "") ui.Error("Error message") ui.Info("Info message") ui.Output("Output message") ui.Running("Running message") ui.Success("Success message") ui.Warn("Warning message") ``` -------------------------------- ### Viewing g Tool Version Information (Shell) Source: https://github.com/voidint/g/blob/master/README.md This command displays detailed version information for the `g` tool itself, including its version number, build timestamp, branch, and commit hash. This is useful for debugging or verifying the installed `g` version. ```shell g version 1.5.0 build: 2023-01-01T21:01:52+08:00 branch: master commit: cec84a3f4f927adb05018731a6f60063fd2fa216 ``` -------------------------------- ### Sample JSON Document for GJSON Path Syntax Source: https://github.com/voidint/g/blob/master/vendor/github.com/tidwall/gjson/README.md This JSON object serves as a sample document to illustrate various GJSON path syntax examples. It includes nested objects, arrays, and keys with special characters, demonstrating common data structures for querying. ```json { "name": {"first": "Tom", "last": "Anderson"}, "age":37, "children": ["Sara","Alex","Jack"], "fav.movie": "Deer Hunter", "friends": [ {"first": "Dale", "last": "Murphy", "age": 44, "nets": ["ig", "fb", "tw"]}, {"first": "Roger", "last": "Craig", "age": 68, "nets": ["fb", "tw"]}, {"first": "Jane", "last": "Murphy", "age": 47, "nets": ["ig", "tw"]} ] } ``` -------------------------------- ### Scraping Web Content with goquery in Go Source: https://github.com/voidint/g/blob/master/vendor/github.com/PuerkitoBio/goquery/README.md This Go example demonstrates how to perform basic web scraping using the goquery library. It fetches an HTML page from a URL, loads its content into a goquery Document, and then uses CSS selectors to find specific elements (article titles) and extract their text. It requires the `net/http` package for fetching and `github.com/PuerkitoBio/goquery` for parsing. ```Go package main import ( "fmt" "log" "net/http" "github.com/PuerkitoBio/goquery" ) func ExampleScrape() { // Request the HTML page. res, err := http.Get("http://metalsucks.net") if err != nil { log.Fatal(err) } defer res.Body.Close() if res.StatusCode != 200 { log.Fatalf("status code error: %d %s", res.StatusCode, res.Status) } // Load the HTML document doc, err := goquery.NewDocumentFromReader(res.Body) if err != nil { log.Fatal(err) } // Find the review items doc.Find(".left-content article .post-title").Each(func(i int, s *goquery.Selection) { // For each item found, get the title title := s.Find("a").Text() fmt.Printf("Review %d: %s\n", i, title) }) } func main() { ExampleScrape() } ``` -------------------------------- ### Extracting Pricing Plan Data with Cascadia in Go Source: https://github.com/voidint/g/blob/master/vendor/github.com/andybalholm/cascadia/README.md This comprehensive Go example demonstrates how to parse an HTML string, use `cascadia` to query elements by CSS selectors, and extract specific data like plan names, prices, user counts, storage, and detail URLs. It includes helper functions for single and multiple queries, and attribute retrieval, showcasing a typical workflow for web scraping or HTML data extraction. ```Go package main import ( "fmt" "log" "strings" "github.com/andybalholm/cascadia" "golang.org/x/net/html" ) var pricingHtml string = `

Free

$0/mo

Pro

$15/mo

Enterprise

$29/mo

` func Query(n *html.Node, query string) *html.Node { sel, err := cascadia.Parse(query) if err != nil { return &html.Node{} } return cascadia.Query(n, sel) } func QueryAll(n *html.Node, query string) []*html.Node { sel, err := cascadia.Parse(query) if err != nil { return []*html.Node{} } return cascadia.QueryAll(n, sel) } func AttrOr(n *html.Node, attrName, or string) string { for _, a := range n.Attr { if a.Key == attrName { return a.Val } } return or } func main() { doc, err := html.Parse(strings.NewReader(pricingHtml)) if err != nil { log.Fatal(err) } fmt.Printf("List of pricing plans:\n\n") for i, p := range QueryAll(doc, "div.card.mb-4.box-shadow") { planName := Query(p, "h4").FirstChild.Data price := Query(p, ".pricing-card-title").FirstChild.Data usersIncluded := Query(p, "li:first-child").FirstChild.Data storage := Query(p, "li:nth-child(2)").FirstChild.Data detailsUrl := AttrOr(Query(p, "li:last-child a"), "href", "(No link available)") fmt.Printf( "Plan #%d\nName: %s\nPrice: %s\nUsers: %s\nStorage: %s\nDetails: %s\n\n", i+1, planName, price, usersIncluded, storage, detailsUrl, ) } } ``` -------------------------------- ### Initializing Global JavaScript Array Source: https://github.com/voidint/g/blob/master/version/testdata/golang_dl_with_rc.html This JavaScript snippet initializes a global array `window.initFuncs`. This array is typically used to store functions that need to be executed once the page has loaded or at a specific point in the application lifecycle, ensuring proper page setup. ```JavaScript window.initFuncs = []; ``` -------------------------------- ### Basic GJSON Path Usage in Go Source: https://github.com/voidint/g/blob/master/vendor/github.com/tidwall/gjson/SYNTAX.md Demonstrates fundamental GJSON path expressions for accessing object properties by name and array elements by index. These paths retrieve specific values or sub-objects from the example JSON. ```go name.last "Anderson" name.first "Tom" age 37 children ["Sara","Alex","Jack"] children.0 "Sara" children.1 "Alex" friends.1 {"first": "Roger", "last": "Craig", "age": 68} friends.1.first "Roger" ``` -------------------------------- ### Wrapping Errors with Context using errors.Wrap in Go Source: https://github.com/voidint/g/blob/master/vendor/github.com/pkg/errors/README.md This example demonstrates how to use `errors.Wrap` from the `pkg/errors` package to add contextual information to an existing error. If `ioutil.ReadAll` fails, the original error `err` is wrapped with the message 'read failed', providing more debugging context. ```Go _, err := ioutil.ReadAll(r) if err != nil { return errors.Wrap(err, "read failed") } ``` -------------------------------- ### Example JSON Lines Document Source: https://github.com/voidint/g/blob/master/vendor/github.com/tidwall/gjson/README.md This snippet demonstrates a multi-line JSON document formatted according to the JSON Lines specification, where each line is a valid, independent JSON object. This format is often used for streaming or processing large datasets line by line. ```JSON {"name": "Gilbert", "age": 61} {"name": "Alexa", "age": 34} {"name": "May", "age": 57} {"name": "Deloise", "age": 44} ``` -------------------------------- ### Compacting JSON with pretty.Ugly in Go Source: https://github.com/voidint/g/blob/master/vendor/github.com/tidwall/pretty/README.md This Go code snippet demonstrates the use of the `pretty.Ugly` function to compact a JSON byte slice (`example`) into a single-line, minimized format. This is useful for reducing payload size, removing unnecessary whitespace, and making JSON less human-readable but more machine-efficient. ```Go result = pretty.Ugly(example) ``` ```JSON {"name":{"first":"Tom","last":"Anderson"},"age":37,"children":["Sara","Alex","Jack"],"fav.movie":"Deer Hunter","friends":[{"first":"Janet","last":"Murphy","age":44}]} ``` -------------------------------- ### Using Match for Pattern Matching in Go Source: https://github.com/voidint/g/blob/master/vendor/github.com/tidwall/match/README.md These examples demonstrate how to use the `match.Match` function to perform simple pattern matching in Go. The function takes a target string and a pattern string, returning a boolean indicating if the target matches the pattern. The '*' wildcard matches any sequence of characters, and '?' matches any single character. ```Go match.Match("hello", "*llo") match.Match("jello", "?ello") match.Match("hello", "h*o") ``` -------------------------------- ### Configuring `g` Environment Variables in PowerShell Profile Source: https://github.com/voidint/g/blob/master/README.md This PowerShell snippet is intended to be added to the user's PowerShell profile (`$PROFILE`) to persistently set environment variables for `g`. It defines `GOROOT` to point to the Go installation managed by `g` and prepends `g`'s binary directory and `GOROOT/bin` to the system `Path` variable, making `g` and Go commands accessible. ```ps1 $env:GOROOT="$HOME\.g\go" $env:Path=-join("$HOME\.g\bin;", "$env:GOROOT\bin;", "$env:Path") ``` -------------------------------- ### Sorting a Collection of Semantic Versions in Go Source: https://github.com/voidint/g/blob/master/vendor/github.com/Masterminds/semver/v3/README.md This example illustrates how to sort a slice of semantic versions using the standard Go `sort` package. It first parses raw version strings into `semver.Version` objects, then uses `sort.Sort` with `semver.Collection` to sort them according to semantic versioning rules. Error handling for parsing is included. ```Go raw := []string{"1.2.3", "1.0", "1.3", "2", "0.4.2",} vs := make([]*semver.Version, len(raw)) for i, r := range raw { v, err := semver.NewVersion(r) if err != nil { t.Errorf("Error parsing version: %s", err) } vs[i] = v } sort.Sort(semver.Collection(vs)) ``` -------------------------------- ### Sanitizing Blackfriday HTML Output with Bluemonday Source: https://github.com/voidint/g/blob/master/vendor/github.com/russross/blackfriday/v2/README.md This Go example demonstrates how to integrate Blackfriday with Bluemonday for sanitizing user-supplied Markdown content. Blackfriday first renders the Markdown to potentially unsafe HTML, which is then passed to Bluemonday's `UGCPolicy()` to remove malicious elements, ensuring safe HTML output. ```Go import ( "github.com/microcosm-cc/bluemonday" "github.com/russross/blackfriday/v2" ) // ... unsafe := blackfriday.Run(input) html := bluemonday.UGCPolicy().SanitizeBytes(unsafe) ``` -------------------------------- ### Mixing and Reusing Go Color Attributes Source: https://github.com/voidint/g/blob/master/vendor/github.com/fatih/color/README.md This example demonstrates creating and combining color attributes. It shows how to create new color objects, add multiple attributes (like foreground color and underline/bold), and mix foreground/background colors, including RGB combinations, for reusable styles. ```Go // Create a new color object c := color.New(color.FgCyan).Add(color.Underline) c.Println("Prints cyan text with an underline.") // Or just add them to New() d := color.New(color.FgCyan, color.Bold) d.Printf("This prints bold cyan %s\n", "too!.") // Mix up foreground and background colors, create new mixes! red := color.New(color.FgRed) boldRed := red.Add(color.Bold) boldRed.Println("This will print text in bold red.") whiteBackground := red.Add(color.BgWhite) whiteBackground.Println("Red text with white background.") // Mix with RGB color codes color.RGB(255, 128, 0).AddBgRGB(0, 0, 0).Println("orange with black background") color.BgRGB(255, 128, 0).AddRGB(255, 255, 255).Println("orange background with white foreground") ``` -------------------------------- ### Tracking I/O Operations with Go Progress Bar Source: https://github.com/voidint/g/blob/master/vendor/github.com/schollz/progressbar/v3/README.md This example illustrates how to use `progressbar` to monitor byte-stream operations, specifically a file download. The `progressbar` acts as an `io.Writer`, allowing `io.Copy` to automatically update the bar based on the bytes transferred from the HTTP response body to both the file and the progress bar. It requires `net/http`, `os`, and `io` packages. ```Go req, _ := http.NewRequest("GET", "https://dl.google.com/go/go1.14.2.src.tar.gz", nil) resp, _ := http.DefaultClient.Do(req) defer resp.Body.Close() f, _ := os.OpenFile("go1.14.2.src.tar.gz", os.O_CREATE|os.O_WRONLY, 0644) defer f.Close() bar := progressbar.DefaultBytes( resp.ContentLength, "downloading", ) io.Copy(io.MultiWriter(f, bar), resp.Body) ``` -------------------------------- ### Controlling Local Color Output for a Color Definition (Go) Source: https://github.com/voidint/g/blob/master/vendor/github.com/fatih/color/README.md This example illustrates how to control color output for a specific 'color.New' instance. It shows how to create a color definition, print text with color, then temporarily disable color for that instance using 'DisableColor()', and re-enable it with 'EnableColor()'. ```Go c := color.New(color.FgCyan) c.Println("Prints cyan text") c.DisableColor() c.Println("This is printed without any color") c.EnableColor() c.Println("This prints again cyan...") ``` -------------------------------- ### Demonstrating YAML Unmarshaling and Marshaling in Go Source: https://github.com/voidint/g/blob/master/vendor/gopkg.in/yaml.v3/README.md This Go example showcases how to use the `gopkg.in/yaml.v3` package to unmarshal YAML data into both a custom Go struct and a generic map, and then marshal these Go types back into YAML. It highlights the use of struct tags like `yaml:"c"` for field renaming and `yaml:",flow"` for compact array representation, and emphasizes that struct fields must be public for unmarshaling. ```Go package main import ( "fmt" "log" "gopkg.in/yaml.v3" ) var data = ` a: Easy! b: c: 2 d: [3, 4] ` // Note: struct fields must be public in order for unmarshal to // correctly populate the data. type T struct { A string B struct { RenamedC int `yaml:"c"` D []int `yaml:",flow"` } } func main() { t := T{} err := yaml.Unmarshal([]byte(data), &t) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("--- t:\n%v\n\n", t) d, err := yaml.Marshal(&t) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("--- t dump:\n%s\n\n", string(d)) m := make(map[interface{}]interface{}) err = yaml.Unmarshal([]byte(data), &m) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("--- m:\n%v\n\n", m) d, err = yaml.Marshal(&m) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("--- m dump:\n%s\n\n", string(d)) } ``` -------------------------------- ### Parsing and Getting Values with GJSON in Go Source: https://github.com/voidint/g/blob/master/vendor/github.com/tidwall/gjson/README.md This Go snippet illustrates three equivalent ways to retrieve a nested value (`name.last`) from a JSON string using GJSON. It highlights the flexibility of chaining `Get` calls on a parsed result, directly getting from the original JSON, or using a single path string for convenience. ```Go gjson.Parse(json).Get("name").Get("last") gjson.Get(json, "name").Get("last") gjson.Get(json, "name.last") ``` -------------------------------- ### Example JSON Payload Source: https://github.com/voidint/g/blob/master/vendor/github.com/tidwall/gjson/SYNTAX.md This JSON object serves as the base data for all subsequent GJSON path examples, demonstrating various data types and nested structures. ```json { "name": {"first": "Tom", "last": "Anderson"}, "age":37, "children": ["Sara","Alex","Jack"], "fav.movie": "Deer Hunter", "friends": [ {"first": "Dale", "last": "Murphy", "age": 44, "nets": ["ig", "fb", "tw"]}, {"first": "Roger", "last": "Craig", "age": 68, "nets": ["fb", "tw"]}, {"first": "Jane", "last": "Murphy", "age": 47, "nets": ["ig", "tw"]} ] } ``` -------------------------------- ### Creating a Basic Interactive Menu in Go Source: https://github.com/voidint/g/blob/master/vendor/github.com/dixonwille/wmenu/v5/README.md This snippet demonstrates how to create a simple interactive menu using `wmenu.NewMenu`. It sets a main action function that executes if a selected option doesn't have its own, defines multiple options, and marks 'Pizza' as the default. The `menu.Run()` method displays the menu and processes user input. ```Go menu := wmenu.NewMenu("What is your favorite food?") menu.Action(func (opts []wmenu.Opt) error {fmt.Printf(opts[0].Text + " is your favorite food."); return nil}) menu.Option("Pizza", nil, true, nil) menu.Option("Ice Cream", nil, false, nil) menu.Option("Tacos", nil, false, func(opt wmenu.Opt) error { fmt.Printf("Tacos are great") return nil }) err := menu.Run() if err != nil{ log.Fatal(err) } ``` -------------------------------- ### Vendoring WMenu Pre Go 1.11 with govendor in Shell Source: https://github.com/voidint/g/blob/master/vendor/github.com/dixonwille/wmenu/v5/README.md This command illustrates how to fetch a specific version of the WMenu library (v4 in this case) using `govendor` for Go projects prior to version 1.11. It ensures stable dependency management by vendoring the specified tag. ```Shell govendor fetch github.com/dixonwille/wmenu@v4 ``` -------------------------------- ### Running gomonkey Tests - Go Source: https://github.com/voidint/g/blob/master/vendor/github.com/agiledragon/gomonkey/v2/README.md These commands navigate into the 'test' directory and then execute the Go tests for gomonkey. The '-gcflags=all=-l' flag is crucial as it disables inlining for all packages, which is a prerequisite for gomonkey's monkey patching to function correctly during testing. ```Go $ cd test $ go test -gcflags=all=-l ``` -------------------------------- ### Using Stateless Gzip Compression with Buffered Writer in Go Source: https://github.com/voidint/g/blob/master/vendor/github.com/klauspost/compress/README.md This Go snippet demonstrates how to initialize a `gzip.Writer` with `StatelessCompression` and wrap it with a `bufio.Writer` to control write sizes. This approach is suitable for scenarios with many concurrent, low-activity compressors, minimizing memory footprint when idle. It shows error handling and proper resource cleanup using `defer`. ```Go // replace 'ioutil.Discard' with your output. gzw, err := gzip.NewWriterLevel(ioutil.Discard, gzip.StatelessCompression) if err != nil { return err } defer gzw.Close() w := bufio.NewWriterSize(gzw, 4096) defer w.Flush() // Write to 'w' ``` -------------------------------- ### Running Benchmarks for goquery in Go Source: https://github.com/voidint/g/blob/master/vendor/github.com/PuerkitoBio/goquery/README.md These commands change the directory to the `goquery` source and then run the `go test` command with the `-bench=".*"` flag. This executes all performance benchmarks for the library, which can take several minutes to complete. ```Shell cd $GOPATH/src/github.com/PuerkitoBio/goquery go test -bench=".*" ```