### Install etcd/clientv3 Go Package Source: https://github.com/stashed/stash/blob/master/vendor/go.etcd.io/etcd/client/v3/README.md Instructions for installing the etcd/clientv3 Go package using go get. It includes a note about pre-release versions and their specific installation commands. ```bash go get go.etcd.io/etcd/client/v3 ``` ```bash go get go.etcd.io/etcd/client/v3@v3.5.0-pre ``` -------------------------------- ### Install OpenCensus Go Library Source: https://github.com/stashed/stash/blob/master/vendor/go.opencensus.io/README.md This command installs the OpenCensus Go library using the go get command. Ensure you have Go 1.8 or later installed. Vendoring or a dependency management tool is recommended. ```bash go get -u go.opencensus.io ``` -------------------------------- ### Install jsonpatch Go Library Source: https://github.com/stashed/stash/blob/master/vendor/github.com/evanphx/json-patch/README.md Instructions for installing the latest and stable versions of the jsonpatch Go library using the go get command. ```bash go get -u github.com/evanphx/json-patch/v5 # Stable Versions: # Version 5: go get -u gopkg.in/evanphx/json-patch.v5 # Version 4: go get -u gopkg.in/evanphx/json-patch.v4 ``` -------------------------------- ### Verify Example Builds After Release Source: https://github.com/stashed/stash/blob/master/vendor/go.opentelemetry.io/otel/RELEASING.md This script, './verify_examples.sh', is used to ensure that example projects build correctly after a new release. It copies examples to a separate directory, removes local 'replace' directives from go.mod, and attempts to build them against the published release. ```shell ./verify_examples.sh ``` -------------------------------- ### Go: Basic fsnotify Watcher Example Source: https://github.com/stashed/stash/blob/master/vendor/github.com/fsnotify/fsnotify/README.md This Go code demonstrates the basic usage of the fsnotify library to create a file system watcher. It sets up a watcher, listens for file events and errors in a goroutine, and adds a directory to monitor. Ensure fsnotify is installed via `go get github.com/fsnotify/fsnotify`. ```go package main import ( "log" "github.com/fsnotify/fsnotify" ) func main() { // Create new watcher. watcher, err := fsnotify.NewWatcher() if err != nil { log.Fatal(err) } defer watcher.Close() // Start listening for events. go func() { for { select { case event, ok := <-watcher.Events: if !ok { return } log.Println("event:", event) if event.Has(fsnotify.Write) { log.Println("modified file:", event.Name) } case err, ok := <-watcher.Errors: if !ok { return } log.Println("error:", err) } } }() // Add a path. err = watcher.Add("/tmp") if err != nil { log.Fatal(err) } // Block main goroutine forever. <-make(chan struct{}) } ``` -------------------------------- ### Initialize Procfs and Get CPU Stats (Go) Source: https://github.com/stashed/stash/blob/master/vendor/github.com/prometheus/procfs/README.md Initializes the proc filesystem and retrieves CPU statistics from /proc/stat. This is a common starting point for gathering system metrics. ```go fs, err := procfs.NewFS("/proc") stats, err := fs.Stat() ``` -------------------------------- ### Install Diskv Go Package Source: https://github.com/stashed/stash/blob/master/vendor/github.com/peterbourgon/diskv/README.md This command installs the diskv Go package using the Go package manager. Ensure you have Go 1 installed. ```bash go get github.com/peterbourgon/diskv ``` -------------------------------- ### Install Swift Go Library Source: https://github.com/stashed/stash/blob/master/vendor/github.com/ncw/swift/README.md Use the 'go get' command to install the Swift Go library. This command fetches and installs the specified package and its dependencies. ```go go get github.com/ncw/swift ``` -------------------------------- ### Diskv Simple Transform Function Example Source: https://github.com/stashed/stash/blob/master/vendor/github.com/peterbourgon/diskv/README.md Illustrates a basic transform function for diskv that places all keys in the same base directory. This function is a starting point for customizing data organization on disk. ```go func SimpleTransform (key string) []string { return []string{} } ``` -------------------------------- ### Install adal Package for Go Source: https://github.com/stashed/stash/blob/master/vendor/github.com/Azure/go-autorest/autorest/adal/README.md Installs the Azure Active Directory authentication library for Go using the go get command. This is the initial step to include the library in your project. ```bash go get -u github.com/Azure/go-autorest/autorest/adal ``` -------------------------------- ### Install blackfriday-tool Source: https://github.com/stashed/stash/blob/master/vendor/github.com/russross/blackfriday/v2/README.md Installs the `blackfriday-tool`, a command-line utility for processing Markdown files. This also installs the Blackfriday library. ```bash go get github.com/russross/blackfriday-tool ``` -------------------------------- ### Install govalidator Package Source: https://github.com/stashed/stash/blob/master/vendor/github.com/asaskevich/govalidator/README.md Installs the govalidator package using the go get command. This is the first step before importing and using the package in your Go project. ```bash go get github.com/asaskevich/govalidator or you can get specified release of the package with `gopkg.in`: go get gopkg.in/asaskevich/govalidator.v10 ``` -------------------------------- ### Basic Structured Logging Example Source: https://github.com/stashed/stash/blob/master/vendor/sigs.k8s.io/controller-runtime/TMP-LOGGING.md Demonstrates how to log a simple message with a variable using structured logging, contrasting it with the standard library's fmt.Printf. ```go log.Printf("starting reconciliation for pod %s/%s", podNamespace, podName) ``` ```go logger.Info("starting reconciliation", "pod", req.NamespacedName) ``` -------------------------------- ### Install go-gitignore Package Source: https://github.com/stashed/stash/blob/master/vendor/github.com/monochromegane/go-gitignore/README.md Provides the command to install the go-gitignore library using the Go module system. This is a prerequisite for using the library in a Go project. ```sh go get github.com/monochromegane/go-gitignore ``` -------------------------------- ### Define and Route a WebService in Go Source: https://github.com/stashed/stash/blob/master/vendor/github.com/emicklei/go-restful/v3/README.md Illustrates the basic setup of a WebService in go-restful, defining its path, supported content types, and a sample GET route with parameters and response types. ```go ws := new(restful.WebService) ws. Path("/users"). Consumes(restful.MIME_XML, restful.MIME_JSON). Produces(restful.MIME_JSON, restful.MIME_XML) ws.Route(ws.GET("/{user-id}").To(u.findUser). Doc("get a user"). Param(ws.PathParameter("user-id", "identifier of the user").DataType("string")), Writes(User{})) ``` -------------------------------- ### Go Server Example for SpdyStream Source: https://github.com/stashed/stash/blob/master/vendor/github.com/moby/spdystream/README.md Provides a Go example for setting up a SpdyStream server that mirrors incoming streams. It listens for TCP connections, establishes a SPDY connection, and uses a mirroring handler to echo data back to clients. Requires the 'github.com/moby/spdystream' package. ```go package main import ( "github.com/moby/spdystream" "net" ) func main() { listener, err := net.Listen("tcp", "localhost:8080") if err != nil { panic(err) } for { conn, err := listener.Accept() if err != nil { panic(err) } spdyConn, err := spdystream.NewConnection(conn, true) if err != nil { panic(err) } go spdyConn.Serve(spdystream.MirrorStreamHandler) } } ``` -------------------------------- ### Install Mergo Go Library Source: https://github.com/stashed/stash/blob/master/vendor/gomodules.xyz/mergo/README.md This command installs the Mergo library using the Go build tool. It is a prerequisite for using Mergo in your Go projects. ```bash go get gomodules.xyz/mergo ``` -------------------------------- ### Go: Start and End a Span for Trace Source: https://github.com/stashed/stash/blob/master/vendor/go.opencensus.io/README.md Illustrates how to start and end a span within a trace using OpenCensus Go. Spans represent individual steps in a distributed request. The `trace.StartSpan` function creates a span, and `defer span.End()` ensures it's properly closed. It utilizes `context.Context` for span propagation. ```go ctx, span := trace.StartSpan(ctx, "cache.Get") defer span.End() // Do work to get from cache. ``` -------------------------------- ### Install Go-MySQL-Driver using go tool Source: https://github.com/stashed/stash/blob/master/vendor/github.com/go-sql-driver/mysql/README.md This command installs the Go-MySQL-Driver package using the Go tool. Ensure Git is installed and in your system's PATH. ```bash go get -u github.com/go-sql-driver/mysql ``` -------------------------------- ### Install Blackfriday v2 Package Source: https://github.com/stashed/stash/blob/master/vendor/github.com/russross/blackfriday/v2/README.md Installs the Blackfriday v2 package using the Go toolchain. This command fetches the package and adds it to your project's module dependencies. ```bash go get github.com/russross/blackfriday/v2 ``` -------------------------------- ### Install Mergo Go Package Source: https://github.com/stashed/stash/blob/master/vendor/github.com/imdario/mergo/README.md This command installs the Mergo library for use in Go projects. It is a prerequisite for utilizing Mergo's functionalities. ```go go get github.com/imdario/mergo ``` -------------------------------- ### Mergo Example: Merging Structs Source: https://github.com/stashed/stash/blob/master/vendor/gomodules.xyz/mergo/README.md A complete, runnable example demonstrating the basic `mergo.Merge` function. It defines two `Foo` structs, merges the source into the destination, and prints the result, showing how fields are updated. ```go package main import ( "fmt" "gomodules.xyz/mergo" ) type Foo struct { A string B int64 } func main() { src := Foo{ A: "one", B: 2, } dest := Foo{ A: "two", } mergo.Merge(&dest, src) fmt.Println(dest) // Will print // {two 2} } ``` -------------------------------- ### Example Usage of Credential Helpers (Bash) Source: https://github.com/stashed/stash/blob/master/vendor/github.com/google/go-containerregistry/pkg/authn/README.md These examples demonstrate how `crane` and `docker` commands interact with configured credential helpers. The output shows the credentials being passed during operations like pulling a manifest or image. ```bash $ crane manifest gcr.io/google-containers/pause > /dev/null {"ServerURL":"","Username":"_dcgcr_1_5_0_token","Secret":""} ``` ```bash $ docker pull gcr.io/google-containers/pause Using default tag: latest {"ServerURL":"","Username":"_dcgcr_1_5_0_token","Secret":""} latest: Pulling from google-containers/pause a3ed95caeb02: Pull complete 4964c72cd024: Pull complete Digest: sha256:a78c2d6208eff9b672de43f880093100050983047b7b0afe0217d3656e1b0d5f Status: Downloaded newer image for gcr.io/google-containers/pause:latest gcr.io/google-containers/pause:latest ``` -------------------------------- ### Start Stash Operator Server in Go Source: https://context7.com/stashed/stash/llms.txt This Go code initializes and runs the main Stash controller. It sets up a signal handler for graceful shutdown, creates operator options, parses command-line flags, completes and validates the options, and then starts the operator's main run loop. Dependencies include the Stash server package and Kubernetes apiserver's generic server utilities. ```go // Start Stash operator package main import ( "io" "os" "stash.appscode.dev/stash/pkg/cmds/server" v "gomodules.xyz/x/version" genericapiserver "k8s.io/apiserver/pkg/server" ) func main() { // Setup signal handler stopCh := genericapiserver.SetupSignalHandler() // Create operator options o := server.NewStashOptions(os.Stdout, os.Stderr) // Parse flags from command line // o.AddFlags(cmd.Flags()) // Complete options with defaults if err := o.Complete(); err != nil { panic(err) } // Validate options if err := o.Validate([]string{}); err != nil { panic(err) } // Run operator if err := o.Run(stopCh); err != nil { panic(err) } } ``` -------------------------------- ### Install NATS Go Client Source: https://github.com/stashed/stash/blob/master/vendor/github.com/nats-io/nats.go/README.md Installs the latest or a specific version of the NATS Go client using the go get command. It also shows how to get the latest major version of the NATS server. ```bash # To get the latest released Go client: go get github.com/nats-io/nats.go@latest # To get a specific version: go get github.com/nats-io/nats.go@v1.39.0 # Note that the latest major version for NATS Server is v2: go get github.com/nats-io/nats-server/v2@latest ``` -------------------------------- ### Shell: Install gofrs/uuid Package Source: https://github.com/stashed/stash/blob/master/vendor/github.com/gofrs/uuid/README.md Installs the gofrs/uuid package using the go get command. This is a prerequisite for using the package in Go projects. ```shell go get github.com/gofrs/uuid ``` -------------------------------- ### Prepare Pre-Release Branch Source: https://github.com/stashed/stash/blob/master/vendor/go.opentelemetry.io/otel/RELEASING.md This command initiates the pre-release process by creating a new branch for release changes. It requires specifying the module set to be released using the MODSET environment variable. ```shell make prerelease MODSET= ``` -------------------------------- ### Zap Logger Quick Start (Go) Source: https://github.com/stashed/stash/blob/master/vendor/go.uber.org/zap/README.md Illustrates the usage of Zap's Logger for maximum performance and type safety. This logger is ideal for performance-critical paths as it avoids serialization overhead and allocations, supporting only structured logging. ```go logger, _ := zap.NewProduction() defer logger.Sync() logger.Info("failed to fetch URL", // Structured context as strongly typed Field values. zap.String("url", url), zap.Int("attempt", 3), zap.Duration("backoff", time.Second), ) ``` -------------------------------- ### Install http2curl Package (Bash) Source: https://github.com/stashed/stash/blob/master/vendor/moul.io/http2curl/v2/README.md Provides the command to install the http2curl Go package using the 'go get' command. This is a prerequisite for using the library in Go projects. ```bash go get moul.io/http2curl ``` -------------------------------- ### Running gRPC Tests Locally (Go) Source: https://github.com/stashed/stash/blob/master/vendor/google.golang.org/grpc/CONTRIBUTING.md Commands to execute local tests for the gRPC project using Go. These include commands for checking vet errors, running standard tests, and running tests in race mode. Ensure you are in the project's root directory before execution. ```bash # Run vet checks, skipping proto generation VET_SKIP_PROTO=1 ./vet.sh # Run standard tests with specified CPU settings and timeout go test -cpu 1,4 -timeout 7m ./... # Run tests in race mode with specified CPU settings and timeout go test -race -cpu 1,4 -timeout 7m ./... ``` -------------------------------- ### Basic Diskv Usage in Go Source: https://github.com/stashed/stash/blob/master/vendor/github.com/peterbourgon/diskv/README.md Demonstrates the fundamental operations of diskv: initializing a store, writing data to a key, reading data by key, and erasing a key-value pair. It uses a flat transform function and a specified cache size. ```go package main import ( "fmt" "github.com/peterbourgon/diskv" ) func main() { // Simplest transform function: put all the data files into the base dir. flatTransform := func(s string) []string { return []string{} } // Initialize a new diskv store, rooted at "my-data-dir", with a 1MB cache. d := diskv.New(diskv.Options{ BasePath: "my-data-dir", Transform: flatTransform, CacheSizeMax: 1024 * 1024, }) // Write three bytes to the key "alpha". key := "alpha" d.Write(key, []byte{'1', '2', '3'}) // Read the value back out of the store. value, _ := d.Read(key) fmt.Printf("%v\n", value) // Erase the key+value from the store (and the disk). d.Erase(key) } ``` -------------------------------- ### Install json-iterator/go via go get Source: https://github.com/stashed/stash/blob/master/vendor/github.com/json-iterator/go/README.md This command demonstrates the standard method for obtaining the json-iterator/go library using Go's built-in package management tool. It fetches the latest stable version of the library and makes it available for use in your Go projects. No specific inputs or outputs are associated with this command, other than the successful installation of the package. ```bash go get github.com/json-iterator/go ``` -------------------------------- ### Apply Multiple JSON Patches using CLI Source: https://github.com/stashed/stash/blob/master/vendor/github.com/evanphx/json-patch/README.md Demonstrates using the `json-patch` command-line tool to apply multiple JSON patch files to a JSON document provided via stdin. The tool can be installed using `go install`. This example shows how to feed a document and two patch files to the CLI tool and receive the modified document as output. ```bash $ go install github.com/evanphx/json-patch/cmd/json-patch $ cat document.json | json-patch -p patch.1.json -p patch.2.json ``` -------------------------------- ### Go Installation Dependencies for Azure Autorest Source: https://github.com/stashed/stash/blob/master/vendor/github.com/Azure/go-autorest/README.md This code block lists the necessary `go get` commands to install the core Azure Autorest libraries and its subpackages. These packages are essential for interacting with Azure services and handling JSON payloads, especially when dealing with advanced features like `omitempty` and pointer manipulation for empty values. ```bash go get github.com/Azure/go-autorest/autorest go get github.com/Azure/go-autorest/autorest/azure go get github.com/Azure/go-autorest/autorest/date go get github.com/Azure/go-autorest/autorest/to ``` -------------------------------- ### Get Credentials for Multiple Registries with Same Helper Source: https://github.com/stashed/stash/blob/master/vendor/github.com/google/go-containerregistry/pkg/authn/README.md Shows how the same credential helper can be used for multiple registries by passing the domain name via STDIN. This example demonstrates acquiring credentials for `eu.gcr.io` using the `gcr` helper. ```bash $ echo "eu.gcr.io" | docker-credential-gcr get {"Username":"_token","Secret":""} ``` -------------------------------- ### Zap SugaredLogger Quick Start (Go) Source: https://github.com/stashed/stash/blob/master/vendor/go.uber.org/zap/README.md Demonstrates how to use Zap's SugaredLogger for flexible, high-performance logging. It supports both structured and printf-style APIs, making it suitable when performance is important but not absolutely critical. ```go logger, _ := zap.NewProduction() defer logger.Sync() // flushes buffer, if any sugar := logger.Sugar() sugar.Infow("failed to fetch URL", // Structured context as loosely typed key-value pairs. "url", url, "attempt", 3, "backoff", time.Second, ) sugar.Infof("Failed to fetch URL: %s", url) ``` -------------------------------- ### Basic Command Execution in Go using go-sh Source: https://github.com/stashed/stash/blob/master/vendor/gomodules.xyz/go-sh/README.md Demonstrates the fundamental usage of go-sh for executing a simple shell command like 'echo'. This is the most basic way to run a command and get its output. ```go package main import "gomodules.xyz/go-sh" func main() { sh.Command("echo", "hello").Run() } ``` -------------------------------- ### Instantiation with Variadic Options in Go Source: https://github.com/stashed/stash/blob/master/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Demonstrates how to create a new instance of a type using variadic functional options. This pattern allows for flexible and extensible configuration during object creation. ```go func NewT(options ...Option) T {…} ``` -------------------------------- ### Install GzipHandler Go Package Source: https://github.com/stashed/stash/blob/master/vendor/github.com/NYTimes/gziphandler/README.md This command installs the gziphandler package using the Go build tool. Ensure you have Go installed and configured correctly. ```bash go get -u github.com/NYTimes/gziphandler ``` -------------------------------- ### Install treeprint Package Source: https://github.com/stashed/stash/blob/master/vendor/github.com/xlab/treeprint/README.md This command installs the treeprint package using the Go build tool. Ensure you have Go installed and configured correctly. ```bash go get github.com/xlab/treeprint ``` -------------------------------- ### Basic NATS Publisher and Subscriber (Go) Source: https://github.com/stashed/stash/blob/master/vendor/github.com/nats-io/nats.go/README.md Demonstrates basic NATS client operations in Go, including connecting to a server, publishing messages, and setting up both asynchronous and synchronous subscribers. It also shows how to handle request-reply patterns and channel-based subscriptions. ```go import "github.com/nats-io/nats.go" import "fmt" import "time" // Connect to a server nc, _ := nats.Connect(nats.DefaultURL) // Simple Publisher nc.Publish("foo", []byte("Hello World")) // Simple Async Subscriber nc.Subscribe("foo", func(m *nats.Msg) { fmt.Printf("Received a message: %s\n", string(m.Data)) }) // Responding to a request message nc.Subscribe("request", func(m *nats.Msg) { m.Respond([]byte("answer is 42")) }) // Simple Sync Subscriber sub, err := nc.SubscribeSync("foo") m, err := sub.NextMsg(timeout) // Channel Subscriber ch := make(chan *nats.Msg, 64) sub, err := nc.ChanSubscribe("foo", ch) msg := <- ch // Unsubscribe sub.Unsubscribe() // Drain sub.Drain() // Requests msg, err := nc.Request("help", []byte("help me"), 10*time.Millisecond) // Replies nc.Subscribe("help", func(m *nats.Msg) { nc.Publish(m.Reply, []byte("I can help!")) }) // Drain connection (Preferred for responders) // Close() not needed if this is called. nc.Drain() // Close connection nc.Close() ``` -------------------------------- ### Go Client Example for SpdyStream Source: https://github.com/stashed/stash/blob/master/vendor/github.com/moby/spdystream/README.md Demonstrates how to create a SpdyStream client in Go to connect to a mirroring server. It handles establishing a connection, creating a new stream, writing data to it, reading a response, and closing the stream. Requires the 'github.com/moby/spdystream' package. ```go package main import ( "fmt" "github.com/moby/spdystream" "net" "net/http" ) func main() { conn, err := net.Dial("tcp", "localhost:8080") if err != nil { panic(err) } spdyConn, err := spdystream.NewConnection(conn, false) if err != nil { panic(err) } go spdyConn.Serve(spdystream.NoOpStreamHandler) stream, err := spdyConn.CreateStream(http.Header{}, nil, false) if err != nil { panic(err) } stream.Wait() fmt.Fprint(stream, "Writing to stream") buf := make([]byte, 25) stream.Read(buf) fmt.Println(string(buf)) stream.Close() } ``` -------------------------------- ### Get opentelemetry-go with Go Get Source: https://github.com/stashed/stash/blob/master/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Retrieves the opentelemetry-go project using `go get`. This command places the project in your Go workspace, typically `${GOPATH}/src/go.opentelemetry.io/otel`. It may display warnings about build constraints, which can be ignored. ```go go get -d go.opentelemetry.io/otel ``` -------------------------------- ### Create etcd/clientv3 Client Source: https://github.com/stashed/stash/blob/master/vendor/go.etcd.io/etcd/client/v3/README.md Demonstrates how to create a new etcd client instance using clientv3.New with configuration options like endpoints and dial timeout. It emphasizes closing the client to prevent resource leaks. ```go cli, err := clientv3.New(clientv3.Config{ Endpoints: []string{"localhost:2379", "localhost:22379", "localhost:32379"}, DialTimeout: 5 * time.Second, }) if err != nil { // handle error! } defer cli.Close() ``` -------------------------------- ### Extract Substring by Range (Substring) Source: https://github.com/stashed/stash/blob/master/vendor/github.com/google/cel-go/ext/README.md The `substring` function extracts a portion of a string based on a numeric start and optional end index. The start index is inclusive, and the end index is exclusive. It's an error to provide invalid ranges (e.g., end < start, negative indices, or indices exceeding string length). ```javascript 'tacocat'.substring(4) // returns 'cat' 'tacocat'.substring(0, 4) // returns 'taco' 'tacocat'.substring(-1) // error 'tacocat'.substring(2, 1) // error ```