### Install sigs.k8s.io/yaml Source: https://github.com/containers/container-libs/blob/main/vendor/sigs.k8s.io/yaml/README.md Install the library using the go get command. ```bash $ go get sigs.k8s.io/yaml ``` -------------------------------- ### Initialize SoftHSM2 Token and Build Example Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/stefanberger/go-pkcs11uri/README.md These commands show how to initialize a SoftHSM2 token using its utility, build the Go example program, and then run the example program with a specific PKCS#11 URI. ```bash $ sudo softhsm2-util --init-token --slot 1 --label test --pin 1234 --so-pin 1234 The token has been initialized and is reassigned to slot 2053753261 $ go build ./... $ sudo ./pkcs11-example 'pkcs11:slot-id=2053753261?module-path=/usr/lib64/pkcs11/libsofthsm2.so&pin-value=1234' 517592df8fec3ad146a79a9af153db2a4d784ec5 ``` -------------------------------- ### Install Grapheme Library Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/clipperhouse/uax29/v2/graphemes/README.md Install the grapheme cluster library using go get. ```bash go get github.com/clipperhouse/uax29/v2/graphemes ``` -------------------------------- ### Install pgzip Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/klauspost/pgzip/README.md Install the pgzip library using go get. Ensure dependencies like 'github.com/klauspost/compress' are up-to-date. ```go go get github.com/klauspost/pgzip/... go get -u github.com/klauspost/compress ``` -------------------------------- ### Install json-iterator/go Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/json-iterator/go/README.md Install the library using the go get command. ```go go get github.com/json-iterator/go ``` -------------------------------- ### Install Mergo Source: https://github.com/containers/container-libs/blob/main/vendor/dario.cat/mergo/README.md Install the Mergo library using go get. Then import it into your Go code. ```go go get dario.cat/mergo // use in your .go code import ( "dario.cat/mergo" ) ``` -------------------------------- ### Install and Run Local Go Doc Site Source: https://github.com/containers/container-libs/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Installs the pkgsite tool and runs a local Go documentation site for previewing package documentation. ```bash go install golang.org/x/pkgsite/cmd/pkgsite@latest pkgsite ``` -------------------------------- ### Basic .containerignore Example Source: https://github.com/containers/container-libs/blob/main/common/docs/containerignore.5.md This example demonstrates basic pattern matching for excluding files and directories. It includes comments and patterns for temporary files. ```ignore # comment */temp* */*/temp* temp? ``` -------------------------------- ### Install Ginkgo Locally Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/onsi/ginkgo/v2/CONTRIBUTING.md Installs the Ginkgo testing framework locally using Go modules. ```bash go install ./... ``` -------------------------------- ### Install Ubuntu Development Tools Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/mattn/go-sqlite3/README.md On Ubuntu, install the 'build-essential' package using apt-get. ```bash sudo apt-get install build-essential ``` -------------------------------- ### Install uuid Package Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/google/uuid/README.md Install the uuid package using the go get command. ```sh go get github.com/google/uuid ``` -------------------------------- ### Install go-sqlite3 Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/mattn/go-sqlite3/README.md Install the go-sqlite3 package using the go get command. Ensure CGO_ENABLED is set to 1 and gcc is available in your PATH. ```bash go get github.com/mattn/go-sqlite3 ``` -------------------------------- ### Install Cobra Library Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/spf13/cobra/README.md Install the latest version of the Cobra library using go get. ```bash go get -u github.com/spf13/cobra@latest ``` -------------------------------- ### Install Gorilla Mux Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/gorilla/mux/README.md Install the gorilla/mux package using the go get command. Ensure your Go toolchain is correctly configured. ```sh go get -u github.com/gorilla/mux ``` -------------------------------- ### Install libseccomp-golang Package Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/seccomp/libseccomp-golang/README.md Use the go get command to install the libseccomp-golang package. This command fetches and installs the specified package and its dependencies. ```go go get github.com/seccomp/libseccomp-golang ``` -------------------------------- ### Example fstab Entry for XFS Project Quotas Source: https://github.com/containers/container-libs/blob/main/storage/docs/containers-storage.conf.5.md This example shows how to configure an XFS file system in /etc/fstab to support project quota controls for container storage. Ensure the 'pquota' option is included. ```bash /dev/podman/podman-var /xfs xfs defaults,pquota 1 2 ``` -------------------------------- ### Install CamelCase Package Source: https://github.com/containers/container-libs/blob/main/common/pkg/report/camelcase/README.md Install the CamelCase package using the go get command. ```bash go get github.com/fatih/camelcase ``` -------------------------------- ### Install YAML Package for Go Source: https://github.com/containers/container-libs/blob/main/vendor/go.yaml.in/yaml/v3/README.md Install the go.yaml.in/yaml/v3 package using the go get command. ```bash go get go.yaml.in/yaml/v3 ``` -------------------------------- ### Install stripansi Package Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/acarl005/stripansi/README.md Use the go get command to install the stripansi package. ```sh $ go get -u github.com/acarl005/stripansi ``` -------------------------------- ### Install GPGME Go Wrapper Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/proglottis/gpgme/README.md Use this command to install or update the GPGME Go wrapper library. ```bash go get -u github.com/proglottis/gpgme ``` -------------------------------- ### Basic Test Script Example Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md Demonstrates creating a file and writing data to it, showing the expected fsnotify events. ```shell watch / echo data >/file Output: create /file write /file ``` -------------------------------- ### Install bbolt Source: https://github.com/containers/container-libs/blob/main/vendor/go.etcd.io/bbolt/README.md Install the bbolt library using go get. This command updates your go.mod and go.sum files. ```sh go get go.etcd.io/bbolt@latest ``` -------------------------------- ### Install GoTree using Go Get Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/disiqueira/gotree/v3/README.md Use this command to install the GoTree module into your Go project. ```bash go get github.com/disiqueira/gotree ``` -------------------------------- ### Example: Copying a Configuration File Between Layers Source: https://github.com/containers/container-libs/blob/main/storage/docs/containers-storage-copy.md This example demonstrates copying a configuration file from one layer to another. The command handles potential ID mapping for the copied content. ```bash containers-storage copy layer-with-mapping:/root/config.txt layer-with-different-mapping:/root/config.txt ``` -------------------------------- ### Example Request with Curl Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/gorilla/mux/README.md Shows how to make a request to the example endpoint using curl. ```bash curl localhost:8080/foo -v ``` -------------------------------- ### Preview Documentation Changes Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/onsi/ginkgo/v2/CONTRIBUTING.md Installs Jekyll dependencies and serves the documentation locally for preview. ```bash bundle && bundle exec jekyll serve ``` -------------------------------- ### Reinstall go-sqlite3 with go install Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/mattn/go-sqlite3/README.md If 'go get' fails with an internal compiler error from gcc, remove the downloaded repository and use 'go install' instead. ```bash go install github.com/mattn/go-sqlite3 ``` -------------------------------- ### Example Default Sysctl Configuration Source: https://github.com/containers/container-libs/blob/main/common/docs/containers.conf.5.md An example of how to configure default sysctls for containers. This specific example sets the net.ipv4.ping_group_range. ```conf default_sysctls = [] Example:"net.ipv4.ping_group_range=0 1000". ``` -------------------------------- ### Example Default Ulimits Configuration Source: https://github.com/containers/container-libs/blob/main/common/docs/containers.conf.5.md This example demonstrates how to set default ulimits for containers, specifying both soft and hard limits for a resource like 'nofile'. ```conf default_ulimits = [] Example: "nofile=1024:2048". ``` -------------------------------- ### Ginkgo Spec Example Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/onsi/ginkgo/v2/README.md A comprehensive example demonstrating a Ginkgo spec for checking out books from a library. It includes BeforeEach, When, Context, It, and SpecTimeout constructs. ```go import ( . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ... ) var _ = Describe("Checking books out of the library", Label("library"), func() { var library *libraries.Library var book *books.Book var valjean *users.User BeforeEach(func() { library = libraries.NewClient() book = &books.Book{ Title: "Les Miserables", Author: "Victor Hugo", } valjean = users.NewUser("Jean Valjean") }) When("the library has the book in question", func() { BeforeEach(func(ctx SpecContext) { Expect(library.Store(ctx, book)).To(Succeed()) }) Context("and the book is available", func() { It("lends it to the reader", func(ctx SpecContext) { Expect(valjean.Checkout(ctx, library, "Les Miserables")).To(Succeed()) Expect(valjean.Books()).To(ContainElement(book)) Expect(library.UserWithBook(ctx, book)).To(Equal(valjean)) }, SpecTimeout(time.Second * 5)) }) Context("but the book has already been checked out", func() { var javert *users.User BeforeEach(func(ctx SpecContext) { javert = users.NewUser("Javert") Expect(javert.Checkout(ctx, library, "Les Miserables")).To(Succeed()) }) It("tells the user", func(ctx SpecContext) { err := valjean.Checkout(ctx, library, "Les Miserables") Expect(err).To(MatchError("Les Miserables is currently checked out")) }, SpecTimeout(time.Second * 5)) It("lets the user place a hold and get notified later", func(ctx SpecContext) { Expect(valjean.Hold(ctx, library, "Les Miserables")).To(Succeed()) Expect(valjean.Holds(ctx)).To(ContainElement(book)) By("when Javert returns the book") Expect(javert.Return(ctx, library, book)).To(Succeed()) By("it eventually informs Valjean") notification := "Les Miserables is ready for pick up" Eventually(ctx, valjean.Notifications).Should(ContainElement(notification)) Expect(valjean.Checkout(ctx, library, "Les Miserables")).To(Succeed()) Expect(valjean.Books(ctx)).To(ContainElement(book)) Expect(valjean.Holds(ctx)).To(BeEmpty()) }, SpecTimeout(time.Second * 10)) }) }) When("the library does not have the book in question", func() { It("tells the reader the book is unavailable", func(ctx SpecContext) { err := valjean.Checkout(ctx, library, "Les Miserables") Expect(err).To(MatchError("Les Miserables is not in the library catalog")) }, SpecTimeout(time.Second * 5)) }) }) ``` -------------------------------- ### ENTRYPOINT with Shell Execution Source: https://github.com/containers/container-libs/blob/main/common/docs/Containerfile.5.md Example of an ENTRYPOINT instruction that executes a command in /bin/sh -c. ```Containerfile FROM ubuntu ENTRYPOINT wc -l - ``` -------------------------------- ### Example Response from Curl Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/gorilla/mux/README.md Illustrates the expected HTTP response headers and body when accessing the example endpoint with curl. ```bash * Trying ::1... * TCP_NODELAY set * Connected to localhost (::1) port 8080 (#0) > GET /foo HTTP/1.1 > Host: localhost:8080 > User-Agent: curl/7.59.0 > Accept: */* > < HTTP/1.1 200 OK < Access-Control-Allow-Methods: GET,PUT,PATCH,OPTIONS < Access-Control-Allow-Origin: * < Date: Fri, 28 Jun 2019 20:13:30 GMT < Content-Length: 3 < Content-Type: text/plain; charset=utf-8 < * Connection #0 to host localhost left intact foo ``` -------------------------------- ### Install bbolt Command Line Utility Source: https://github.com/containers/container-libs/blob/main/vendor/go.etcd.io/bbolt/README.md Install the bbolt command line utility. This command places the executable in your $GOBIN path. ```sh go install go.etcd.io/bbolt/cmd/bbolt@latest ``` -------------------------------- ### Example TLS Details Configuration Source: https://github.com/containers/container-libs/blob/main/image/docs/containers-tls-details.yaml.5.md This YAML snippet shows a complete example of a TLS details parameter file, specifying the minimum TLS version, allowed cipher suites, and named groups. ```yaml minVersion: "1.2" cipherSuites: - "TLS_AES_128_GCM_SHA256" - "TLS_CHACHA20_POLY1305_SHA256" namedGroups: - "secp256r1" - "secp384r1" - "x25519" ``` -------------------------------- ### Constructor Functions for Dog and Bird Source: https://github.com/containers/container-libs/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Example constructor functions for `Dog` and `Bird` that accept specific options for their respective types. ```go func NewDog(name string, o ...DogOption) Dog {…} func NewBird(name string, o ...BirdOption) Bird {…} ``` -------------------------------- ### Platform-Specific Test Example Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md Illustrates how to write tests that are specific to certain operating systems, like Windows. ```shell watch / touch /file Output: # Tested if nothing else matches create /file # Windows-specific test. windows: write /file ``` -------------------------------- ### Full Mux Server Example Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/gorilla/mux/README.md A complete, runnable Go program demonstrating a basic web server using Gorilla Mux. It sets up a single route '/' that responds with 'Gorilla!'. ```go package main import ( "net/http" "log" "github.com/gorilla/mux" ) func YourHandler(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Gorilla!\n")) } func main() { r := mux.NewRouter() // Routes consist of a path and a handler function. r.HandleFunc("/", YourHandler) // Bind to a port and pass our router in log.Fatal(http.ListenAndServe(":8000", r)) } ``` -------------------------------- ### Iterating Over All Keys in a Bucket Source: https://github.com/containers/container-libs/blob/main/vendor/go.etcd.io/bbolt/README.md Demonstrates how to iterate through all key-value pairs in a bucket sequentially using a cursor, starting from the first key. ```go db.View(func(tx *bolt.Tx) error { // Assume bucket exists and has keys b := tx.Bucket([]byte("MyBucket")) c := b.Cursor() for k, v := c.First(); k != nil; k, v = c.Next() { fmt.Printf("key=%s, value=%s\n", k, v) } return nil }) ``` -------------------------------- ### Example 2: Configuration File Contents and Precedence Source: https://github.com/containers/container-libs/blob/main/common/docs/containers-config.5.md Demonstrates the content of various configuration files and their effective precedence, highlighting overridden files. ```text /usr/share/containers/containers.conf (overridden by /etc/containers/containers.conf): field_1 = a ``` ```text /etc/containers/containers.conf: field_2 = b ``` ```text /usr/share/containers/containers.conf.d/10-vendor.conf (overridden by $XDG_CONFIG_HOME/containers/containers.conf.d/10-vendor.conf): field_3 = c ``` ```text /usr/share/containers/containers.conf.d/99-important.conf: field_4 = d ``` ```text /usr/share/containers/containers.rootless.conf.d/50-my.conf: field_5 = e ``` ```text $XDG_CONFIG_HOME/containers/containers.conf.d/10-vendor.conf: field_3 = c ``` -------------------------------- ### Example 1: Configuration File Precedence Source: https://github.com/containers/container-libs/blob/main/common/docs/containers-config.5.md Illustrates the effective loading order of configuration files, showing which files are overridden and therefore not read. ```text - /usr/share/containers/containers.conf (overridden by $XDG_CONFIG_HOME/containers/containers.conf and thus not read) - $XDG_CONFIG_HOME/containers/containers.conf - /usr/share/containers/containers.conf.d/00-vendor.conf - /etc/containers/containers.conf.d/50-myconf.conf (overridden by $XDG_CONFIG_HOME/containers/containers.conf.d/50-myconf.conf and thus not read) - $XDG_CONFIG_HOME/containers/containers.conf.d/50-myconf.conf - /usr/share/containers/containers.conf.d/99-conf.conf ``` -------------------------------- ### Standard OpenFile vs. SecureJoin Example Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/cyphar/filepath-securejoin/README.md Illustrates the standard, less secure way of joining paths and opening files, which the securejoin library aims to improve upon. ```go path, err := securejoin.SecureJoin(root, unsafePath) file, err := os.OpenFile(path, unix.O_PATH|unix.O_CLOEXEC) ``` -------------------------------- ### Standard MkdirAll vs. SecureJoin Example Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/cyphar/filepath-securejoin/README.md Shows the conventional method for creating directories using SecureJoin, highlighting the security concerns addressed by the library's MkdirAll function. ```go path, err := securejoin.SecureJoin(root, unsafePath) err = os.MkdirAll(path, mode) ``` -------------------------------- ### List All Docker Containers in Go Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/moby/moby/client/README.md Initializes a Docker client from environment variables, sets a custom User-Agent, and lists all containers (stopped and running) using the ContainerList API. Demonstrates basic client setup and container enumeration. ```go package main import ( "context" "fmt" "github.com/moby/moby/client" ) func main() { // Create a new client with "client.FromEnv" (configuring the client // from commonly used environment variables such as DOCKER_HOST and // DOCKER_API_VERSION) and set a custom User-Agent. // // API-version negotiation is enabled by default to allow downgrading // the API version when connecting with an older daemon version. apiClient, err := client.New( client.FromEnv, client.WithUserAgent("my-application/1.0.0"), ) if err != nil { panic(err) } defer apiClient.Close() // List all containers (both stopped and running). result, err := apiClient.ContainerList(context.Background(), client.ContainerListOptions{ All: true, }) if err != nil { panic(err) } // Print each container's ID, status and the image it was created from. fmt.Printf("%s %-22s %s\n", "ID", "STATUS", "IMAGE") for _, ctr := range result.Items { fmt.Printf("%s %-22s %s\n", ctr.ID, ctr.Status, ctr.Image) } } ``` -------------------------------- ### Parallel Compression Example Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/klauspost/pgzip/README.md Demonstrates basic parallel compression using pgzip. The concurrency can be tuned using SetConcurrency to control block size and parallel processing. ```go var b bytes.Buffer w := gzip.NewWriter(&b) w.SetConcurrency(100000, 10) w.Write([]byte("hello, world\n")) w.Close() ``` -------------------------------- ### Registries Configuration Sections Source: https://github.com/containers/container-libs/blob/main/image/docs/containers-registries.conf.5.md Example configuration for defining searchable, insecure, and blocked registries. This setup allows granular control over which registries are trusted and accessible. ```TOML [registries.search] registries = ['registry1.com', 'registry2.com'] [registries.insecure] registries = ['registry3.com'] [registries.block] registries = ['registry.untrusted.com', 'registry.unsafe.com'] ``` -------------------------------- ### ADD Instruction Example Source: https://github.com/containers/container-libs/blob/main/common/docs/Containerfile.5.md Copies files or directories from a source to a destination within the container. Supports unpacking of local compressed files. ```Containerfile ADD ["",... ""] ``` -------------------------------- ### Install SQLite3 on macOS Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/mattn/go-sqlite3/README.md Use Homebrew to install the sqlite3 dependency on macOS. ```bash brew install sqlite3 ``` -------------------------------- ### Including Specific Files Source: https://github.com/containers/container-libs/blob/main/common/docs/containerignore.5.md This example shows how to include specific files by first excluding everything with '*' and then using negation patterns to include desired files. ```ignore * !important.txt !important/ ``` -------------------------------- ### Create, Snapshot, Clone, and Destroy ZFS Datasets Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/mistifyio/go-zfs/v4/README.md This snippet demonstrates the basic lifecycle of ZFS datasets: creating a filesystem, taking a snapshot, cloning the snapshot, and then destroying the created datasets. Assumes a ZFS pool named 'test' exists. Error handling is omitted for brevity. ```go //assuming a zpool named test //error handling omitted f, err := zfs.CreateFilesystem("test/snapshot-test", nil) ok(t, err) s, err := f.Snapshot("test", nil) ok(t, err) // snapshot is named "test/snapshot-test@test" c, err := s.Clone("test/clone-test", nil) err := c.Destroy() err := s.Destroy() err := f.Destroy() ``` -------------------------------- ### Build Go with Multiple SQLite Features Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/mattn/go-sqlite3/README.md Example command to build the go-sqlite3 library with multiple SQLite features enabled simultaneously. Features are space-delimited. ```bash go build -tags "icu json1 fts5 secure_delete" ``` -------------------------------- ### Install Fedora Development Tools Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/mattn/go-sqlite3/README.md On Fedora, install the 'Development Tools' and 'Development Libraries' groups using yum. ```bash sudo yum groupinstall "Development Tools" "Development Libraries" ``` -------------------------------- ### Install jsonschema CLI tool Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/santhosh-tekuri/jsonschema/v6/README.md Install the 'jv' command-line tool for schema validation using Go modules. ```bash go install github.com/santhosh-tekuri/jsonschema/cmd/jv@latest ``` -------------------------------- ### Example Device Mapping Source: https://github.com/containers/container-libs/blob/main/common/docs/containers.conf.5.md Shows how to map a host device to a container device with specified permissions. The format is 'device-on-host:device-on-container:permissions'. ```conf devices = [] List of devices. Specified as 'device-on-host:device-on-container:permissions'. Example: "/dev/sdc:/dev/xvdc:rwm". ``` -------------------------------- ### Commit Message Format Example Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/godbus/dbus/v5/CONTRIBUTING.md An example demonstrating the required format for commit messages, including subject, body, and footer. ```git scripts: add the test-cluster command this uses tmux to setup a test cluster that you can easily kill and start for debugging. Fixes #38 ``` -------------------------------- ### Go Example: Manipulating Network Namespaces Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/vishvananda/netns/README.md Demonstrates how to save the current network namespace, create a new one, perform operations within it (like listing interfaces), and then switch back to the original namespace. Requires root privileges to run. ```go package main import ( "fmt" "net" "runtime" "github.com/vishvananda/netns" ) func main() { // Lock the OS Thread so we don't accidentally switch namespaces runtime.LockOSThread() defer runtime.UnlockOSThread() // Save the current network namespace origns, _ := netns.Get() defer origns.Close() // Create a new network namespace newns, _ := netns.New() defer newns.Close() // Do something with the network namespace ifaces, _ := net.Interfaces() fmt.Printf("Interfaces: %v\n", ifaces) // Switch back to the original namespace netns.Set(origns) } ``` -------------------------------- ### Basic fsnotify Watcher Example Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/fsnotify/fsnotify/README.md This Go code demonstrates how to create a new fsnotify watcher, set up goroutines to listen for events and errors, and add a directory to watch. It includes essential error handling and resource cleanup. ```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{}) } ``` -------------------------------- ### Install Cobra CLI Generator Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/spf13/cobra/README.md Install the cobra-cli command line program, used for generating Cobra application scaffolding. ```bash go install github.com/spf13/cobra-cli@latest ``` -------------------------------- ### Install godbus/dbus v5 Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/godbus/dbus/v5/README.md Install the godbus/dbus v5 package using the Go tool. Requires Go 1.20 or later. ```go go get github.com/godbus/dbus/v5 ``` -------------------------------- ### Logfmt Formatter Output Example (No TTY) Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/sirupsen/logrus/README.md Example output using the default TextFormatter when a TTY is not attached, compatible with the logfmt format. ```text time="2015-03-26T01:27:38-04:00" level=debug msg="Started observing beach" animal=walrus number=8 time="2015-03-26T01:27:38-04:00" level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10 time="2015-03-26T01:27:38-04:00" level=warning msg="The group's number increased tremendously!" number=122 omg=true time="2015-03-26T01:27:38-04:00" level=debug msg="Temperature changes" temperature=-4 time="2015-03-26T01:27:38-04:00" level=panic msg="It's over 9000!" animal=orca size=9009 time="2015-03-26T01:27:38-04:00" level=fatal msg="The ice breaks!" err=&{0x2082280c0 map[animal:orca size:9009] 2015-03-26 01:27:38.441574009 -0400 EDT panic It's over 9000!} number=100 omg=true ``` -------------------------------- ### Basic Promptui Select Example Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/manifoldco/promptui/README.md Illustrates a basic Promptui select prompt allowing users to choose an item from a predefined list. Handles potential errors during prompt execution. ```go package main import ( "fmt" "github.com/manifoldco/promptui" ) func main() { prompt := promptui.Select{ Label: "Select Day", Items: []string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}, } _, result, err := prompt.Run() if err != nil { fmt.Printf("Prompt failed %v\n", err) return } fmt.Printf("You choose %q\n", result) } ``` -------------------------------- ### SQLite DSN Example Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/mattn/go-sqlite3/README.md Example of a DSN string for configuring a SQLite database connection, specifying the database file and connection options. ```text file:test.db?cache=shared&mode=memory ``` -------------------------------- ### CMD Shell Form Example Source: https://github.com/containers/container-libs/blob/main/common/docs/Containerfile.5.md An example of the CMD instruction using the shell form, where the command is executed within /bin/sh -c. ```Containerfile CMD echo "This is a test." | wc - ``` -------------------------------- ### Example of Old SecureJoin Implementation using chroot Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/cyphar/filepath-securejoin/README.md This Go code demonstrates a basic implementation of SecureJoin using the `chroot` command on GNU/Linux systems. It is provided for historical context and highlights the limitations of the old API. ```Go package securejoin import ( "os/exec" "path/filepath" ) func SecureJoin(root, unsafePath string) (string, error) { unsafePath = string(filepath.Separator) + unsafePath cmd := exec.Command("chroot", root, "readlink", "--canonicalize-missing", "--no-newline", unsafePath) output, err := cmd.CombinedOutput() if err != nil { return "", err } expanded := string(output) return filepath.Join(root, expanded), nil } ``` -------------------------------- ### Registry Authentication with Multiple Paths Source: https://github.com/containers/container-libs/blob/main/image/docs/containers-auth.json.5.md This example demonstrates how to configure multiple credentials for a single registry, 'my-registry.local', by specifying different repository paths. This allows for more granular control over authentication. ```json { "auths": { "my-registry.local/foo/bar/image": { "auth": "…" }, "my-registry.local/foo": { "auth": "…" }, "my-registry.local": { "auth": "…" }, } } ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/containers/container-libs/blob/main/image/README.md Install GPGME and libassuan development libraries for Fedora, or GPGME for macOS. These are required for building the image library. ```shell Fedora$ dnf install gpgme-devel libassuan-devel macOS$ brew install gpgme ``` -------------------------------- ### Run golangci-lint Locally Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/Microsoft/go-winio/README.md Install and run golangci-lint from the repository root to check code quality. Use flags to control the verbosity of the output. ```shell # use . or specify a path to only lint a package # to show all lint errors, use flags "--max-issues-per-linter=0 --max-same-issues=0" > golangci-lint run ./... ``` -------------------------------- ### New Function Signature with Options Source: https://github.com/containers/container-libs/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Demonstrates the signature for a constructor function that accepts variadic `Option` arguments for configuration. ```go func NewT(options ...Option) T {…} ``` -------------------------------- ### Install Alpine Linux Development Tools Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/mattn/go-sqlite3/README.md Before building on Alpine Linux, install the necessary GCC and musl development packages using apk. ```bash apk add --update gcc musl-dev ``` -------------------------------- ### JSON Formatter Output Example Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/sirupsen/logrus/README.md Example output when using the JSON formatter, suitable for parsing by log aggregation systems like Logstash or Splunk. ```text {"animal":"walrus","level":"info","msg":"A group of walrus emerges from the ocean","size":10,"time":"2014-03-10 19:57:38.562264131 -0400 EDT"} {"level":"warning","msg":"The group's number increased tremendously!", "number":122,"omg":true,"time":"2014-03-10 19:57:38.562471297 -0400 EDT"} {"animal":"walrus","level":"info","msg":"A giant walrus appears!", "size":10,"time":"2014-03-10 19:57:38.562500591 -0400 EDT"} {"animal":"walrus","level":"info","msg":"Tremendously sized cow enters the ocean.", "size":9,"time":"2014-03-10 19:57:38.562527896 -0400 EDT"} {"level":"fatal","msg":"The ice breaks!","number":100,"omg":true, "time":"2014-03-10 19:57:38.562543128 -0400 EDT"} ``` -------------------------------- ### Build URL with Host and Query Variables Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/gorilla/mux/README.md Define a route with host, path, and query variables, then build a complete URL including these parameters. Ensure all defined variables are provided. ```go r := mux.NewRouter() r.Host("{subdomain}.example.com"). Path("/articles/{category}/{id:[0-9]+}"). Queries("filter", "{filter}"). HandlerFunc(ArticleHandler). Name("article") // url.String() will be "http://news.example.com/articles/technology/42?filter=gorilla" url, err := r.Get("article").URL("subdomain", "news", "category", "technology", "id", "42", "filter", "gorilla") ``` -------------------------------- ### SQL Examples for User Management Source: https://github.com/containers/container-libs/blob/main/vendor/github.com/mattn/go-sqlite3/README.md Demonstrates SQL commands for managing users in an authenticated SQLite database. Includes adding an admin user, changing a user's password, and deleting a user. ```sql SELECT auth_user_add('admin2', 'admin2', 1); ``` ```sql SELECT auth_user_change('user', 'userpassword', 0); ``` ```sql SELECT user_delete('user'); ```