### Run Registry with Example Configuration Source: https://github.com/notaryproject/notary/blob/master/vendor/github.com/docker/distribution/BUILDING.md Starts the registry server using a provided example configuration file. This command will output log messages indicating the listening address and debug server status. ```bash $GOPATH/bin/registry serve $GOPATH/src/github.com/docker/distribution/cmd/registry/config-example.yml ``` -------------------------------- ### Install gRPC-Go Source: https://github.com/notaryproject/notary/blob/master/vendor/google.golang.org/grpc/README.md Installs the gRPC-Go package using the go get command. This is the standard way to fetch dependencies in Go. ```console $ go get -u google.golang.org/grpc ``` -------------------------------- ### Configuring Notary Client with Bash Alias Source: https://github.com/notaryproject/notary/blob/master/docs/getting_started.md Provides an example of creating a bash alias to simplify Notary commands by preconfiguring the server URL and trust directory flags (`-s` and `-d`). ```bash alias dockernotary="notary -s https://notary.docker.io -d ~/.docker/trust" ``` -------------------------------- ### Installation and Testing Source: https://github.com/notaryproject/notary/blob/master/vendor/github.com/spf13/pflag/README.md Provides instructions on how to install the pflag library using `go get` and how to run its tests using `go test`. These are essential steps for integrating pflag into a Go project. ```go # Install pflag go get github.com/spf13/pflag # Run tests go test github.com/spf13/pflag ``` -------------------------------- ### Install Registry Command using Go Source: https://github.com/notaryproject/notary/blob/master/vendor/github.com/docker/distribution/BUILDING.md Installs the registry command-line tool from the latest source repository using `go get`. This command fetches and installs the specified package and its dependencies into your Go workspace. ```bash go get github.com/docker/distribution/cmd/registry ``` -------------------------------- ### Installation and Upgrade Go Properties Library Source: https://github.com/notaryproject/notary/blob/master/vendor/github.com/magiconair/properties/README.md Provides the necessary commands to install and upgrade the properties Go library using the go get command. It also includes instructions for installing the go-check testing library. ```bash $ go get -u github.com/magiconair/properties $ go get -u gopkg.in/check.v1 ``` -------------------------------- ### Install pq Driver Source: https://github.com/notaryproject/notary/blob/master/vendor/github.com/lib/pq/README.md This snippet shows how to install the pq PostgreSQL driver for Go using the go get command. It's a prerequisite for using the driver with the database/sql package. ```go go get github.com/lib/pq ``` -------------------------------- ### Install go-sqlite3 Source: https://github.com/notaryproject/notary/blob/master/vendor/github.com/mattn/go-sqlite3/README.md Installs the go-sqlite3 package using the go get command. Requires CGO_ENABLED=1 and a GCC compiler. ```go go get github.com/mattn/go-sqlite3 ``` -------------------------------- ### Install pkg/errors Source: https://github.com/notaryproject/notary/blob/master/vendor/github.com/pkg/errors/README.md Installs the pkg/errors package using the go get command. ```go go get github.com/pkg/errors ``` -------------------------------- ### Installation Source: https://github.com/notaryproject/notary/blob/master/vendor/github.com/go-sql-driver/mysql/README.md Installs the Go-MySQL-Driver using the go tool. Requires Git to be installed and in the system's PATH. ```bash go get -u github.com/go-sql-driver/mysql ``` -------------------------------- ### Notary CLI Commands Source: https://github.com/notaryproject/notary/blob/master/docs/getting_started.md Reference for common Notary CLI commands used for managing trust data. Includes commands for listing tags, removing tags, checking status, and publishing changes. ```APIDOC Notary CLI Commands: list: Usage: notary -s -d list Description: Lists all signed tags for a given repository. Parameters: -s, --server: The Notary server URL. -d, --trust-dir: The directory containing trust data. repository: The Docker Hub repository (e.g., docker.io/library/alpine). remove: Usage: notary -s -d remove Description: Stages a tag for removal from the repository's trust data. Parameters: -s, --server: The Notary server URL. -d, --trust-dir: The directory containing trust data. repository: The Docker Hub repository. tag: The tag to remove. Note: Removal is staged and requires `publish` to take effect. status: Usage: notary -d status Description: Displays any unpublished changes staged for a repository. Parameters: -d, --trust-dir: The directory containing trust data. repository: The Docker Hub repository. Note: This is an offline operation. publish: Usage: notary -s -d publish Description: Publishes staged changes (like removals) to the Notary server. Parameters: -s, --server: The Notary server URL. -d, --trust-dir: The directory containing trust data. repository: The Docker Hub repository. ``` -------------------------------- ### Install gorilla/mux Source: https://github.com/notaryproject/notary/blob/master/vendor/github.com/gorilla/mux/README.md Installs the gorilla/mux package using the Go toolchain. Ensure your Go environment is correctly configured. ```go go get -u github.com/gorilla/mux ``` -------------------------------- ### Cobra CLI Application Example Source: https://github.com/notaryproject/notary/blob/master/vendor/github.com/spf13/cobra/user_guide.md A complete Go program demonstrating the creation of a multi-command CLI application using Cobra. It includes nested commands, flags, and basic argument validation. ```go package main import ( "fmt" "strings" "github.com/spf13/cobra" ) func main() { var echoTimes int var cmdPrint = &cobra.Command{ Use: "print [string to print]", Short: "Print anything to the screen", Long: `print is for printing anything back to the screen. For many years people have printed back to the screen.`, Args: cobra.MinimumNArgs(1), Run: func(cmd *cobra.Command, args []string) { fmt.Println("Print: " + strings.Join(args, " ")) }, } var cmdEcho = &cobra.Command{ Use: "echo [string to echo]", Short: "Echo anything to the screen", Long: `echo is for echoing anything back. Echo works a lot like print, except it has a child command.`, Args: cobra.MinimumNArgs(1), Run: func(cmd *cobra.Command, args []string) { fmt.Println("Echo: " + strings.Join(args, " ")) }, } var cmdTimes = &cobra.Command{ Use: "times [string to echo]", Short: "Echo anything to the screen more times", Long: `echo things multiple times back to the user by providing a count and a string.`, Args: cobra.MinimumNArgs(1), Run: func(cmd *cobra.Command, args []string) { for i := 0; i < echoTimes; i++ { fmt.Println("Echo: " + strings.Join(args, " ")) } }, } cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input") var rootCmd = &cobra.Command{Use: "app"} rootCmd.AddCommand(cmdPrint, cmdEcho) cmdEcho.AddCommand(cmdTimes) rootCmd.Execute() } ``` -------------------------------- ### Install mapstructure Source: https://github.com/notaryproject/notary/blob/master/vendor/github.com/mitchellh/mapstructure/README.md Standard Go installation command to get the mapstructure library. ```shell go get github.com/mitchellh/mapstructure ``` -------------------------------- ### Local Notary Server Setup Source: https://github.com/notaryproject/notary/blob/master/README.md Steps to set up a local Notary server and signer using Docker Compose. This involves cloning the repository, building Docker images, starting services, and copying configuration files and certificates to the local Notary directory. ```bash $ docker-compose build $ docker-compose up -d $ mkdir -p ~/.notary && cp cmd/notary/config.json cmd/notary/root-ca.crt ~/.notary ``` -------------------------------- ### Cobra Command Hooks Example Source: https://github.com/notaryproject/notary/blob/master/vendor/github.com/spf13/cobra/user_guide.md Demonstrates the execution order of PersistentPreRun, PreRun, Run, PostRun, and PersistentPostRun hooks in a root command and its subcommand using Go and the Cobra library. Shows how persistent hooks are inherited. ```go package main import ( "fmt" "github.com/spf13/cobra" ) func main() { var rootCmd = &cobra.Command{ Use: "root [sub]", Short: "My root command", PersistentPreRun: func(cmd *cobra.Command, args []string) { fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n", args) }, PreRun: func(cmd *cobra.Command, args []string) { fmt.Printf("Inside rootCmd PreRun with args: %v\n", args) }, Run: func(cmd *cobra.Command, args []string) { fmt.Printf("Inside rootCmd Run with args: %v\n", args) }, PostRun: func(cmd *cobra.Command, args []string) { fmt.Printf("Inside rootCmd PostRun with args: %v\n", args) }, PersistentPostRun: func(cmd *cobra.Command, args []string) { fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n", args) }, } var subCmd = &cobra.Command{ Use: "sub [no options!]", Short: "My subcommand", PreRun: func(cmd *cobra.Command, args []string) { fmt.Printf("Inside subCmd PreRun with args: %v\n", args) }, Run: func(cmd *cobra.Command, args []string) { fmt.Printf("Inside subCmd Run with args: %v\n", args) }, PostRun: func(cmd *cobra.Command, args []string) { fmt.Printf("Inside subCmd PostRun with args: %v\n", args) }, PersistentPostRun: func(cmd *cobra.Command, args []string) { fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n", args) }, } rootCmd.AddCommand(subCmd) rootCmd.SetArgs([]string{}) rootCmd.Execute() fmt.Println() rootCmd.SetArgs([]string{"sub", "arg1", "arg2"}) rootCmd.Execute() } ``` -------------------------------- ### Install TOML Parser Source: https://github.com/notaryproject/notary/blob/master/vendor/github.com/BurntSushi/toml/README.md Installs the TOML parser package for Go using the go get command. ```bash go get github.com/BurntSushi/toml ``` -------------------------------- ### List Signed Tags in a Docker Hub Repository Source: https://github.com/notaryproject/notary/blob/master/docs/getting_started.md This command lists all signed tags for a specified Docker Hub repository. It requires the Notary server address and the trust directory path. The output includes tag names, digests, sizes, and roles. ```bash $ notary -s https://notary.docker.io -d ~/.docker/trust list docker.io/library/alpine NAME DIGEST SIZE (BYTES) ROLE ------------------------------------------------------------------------------------------------------ 2.6 e9cec9aec697d8b9d450edd32860ecd363f2f3174c8338beb5f809422d182c63 1374 targets 2.7 9f08005dff552038f0ad2f46b8e65ff3d25641747d3912e3ea8da6785046561a 1374 targets 3.1 e876b57b2444813cd474523b9c74aacacc238230b288a22bccece9caf2862197 1374 targets 3.2 4a8c62881c6237b4c1434125661cddf09434d37c6ef26bf26bfaef0b8c5e2f05 1374 targets 3.3 2d4f890b7eddb390285e3afea9be98a078c2acd2fb311da8c9048e3d1e4864d3 1374 targets edge 878c1b1d668830f01c2b1622ebf1656e32ce830850775d26a387b2f11f541239 1374 targets latest 24a36bbc059b1345b7e8be0df20f1b23caa3602e85d42fff7ecd9d0bd255de56 1377 targets ``` -------------------------------- ### Install RethinkDB-go Driver Source: https://github.com/notaryproject/notary/blob/master/vendor/gopkg.in/rethinkdb/rethinkdb-go.v6/README.md Installs the RethinkDB-go driver using the go get command. Replace 'v6' with the desired major version. ```go go get gopkg.in/rethinkdb/rethinkdb-go.v6 ``` -------------------------------- ### Cobra Command Suggestion Example (CLI) Source: https://github.com/notaryproject/notary/blob/master/vendor/github.com/spf13/cobra/user_guide.md Shows the output of Cobra's automatic command suggestions when an unknown command is entered, demonstrating how it suggests similar commands based on Levenshtein distance. ```bash $ hugo srever Error: unknown command "srever" for "hugo" Did you mean this? server Run 'hugo --help' for usage. ``` -------------------------------- ### Cobra CLI Customization Functions Source: https://github.com/notaryproject/notary/blob/master/vendor/github.com/spf13/cobra/user_guide.md Provides Go code examples for customizing the help and usage functionalities of a Cobra CLI application. These functions allow developers to define their own help commands, help functions, help templates, and usage templates. ```go cmd.SetHelpCommand(cmd *Command) cmd.SetHelpFunc(f func(*Command, []string)) cmd.SetHelpTemplate(s string) cmd.SetUsageFunc(f func(*Command) error) cmd.SetUsageTemplate(s string) ``` -------------------------------- ### Delete a Tag and Publish Changes Source: https://github.com/notaryproject/notary/blob/master/docs/getting_started.md This sequence of commands demonstrates how to stage a tag for deletion and then publish the changes to the Notary server. The `remove` command stages the deletion, `status` shows pending changes, and `publish` applies them. ```bash $ notary -s https://notary.docker.io -d ~/.docker/trust remove docker.io/library/alpine 2.6 Removal of 2.6 from docker.io/library/alpine staged for next publish. $ notary -d ~/.docker/trust status docker.io/library/alpine Unpublished changes for docker.io/library/alpine: # ACTION SCOPE TYPE PATH - ------ ----- ---- ---- 0 delete targets target 2.6 $ notary -s https://notary.docker.io -d ~/.docker/trust publish docker.io/library/alpine ``` -------------------------------- ### Notary Naming Convention for Docker Hub Source: https://github.com/notaryproject/notary/blob/master/docs/getting_started.md Explains the Globally Unique Names (GUNs) format required when using the Notary client with Docker Hub repositories. This format ensures proper identification of trust collections in a multi-tenant environment. ```markdown For official images (identifiable by the "Official Repository" moniker), the image name as displayed on Docker Hub, prefixed with `docker.io/library/`. For example, if you would normally type `docker pull ubuntu` you must enter `notary docker.io/library/ubuntu`. - For all other images, the image name as displayed on Docker Hub, prefixed by `docker.io`. ``` -------------------------------- ### MySQL Connection String Examples Source: https://github.com/notaryproject/notary/blob/master/vendor/github.com/go-sql-driver/mysql/README.md Provides various examples of MySQL connection strings for different scenarios, including Unix sockets, TCP connections with authentication, IPv6, remote hosts (like Amazon RDS), Google Cloud SQL, and default configurations. ```go user@unix(/path/to/socket)/dbname root:pw@unix(/tmp/mysql.sock)/myDatabase?loc=Local user:password@tcp(localhost:5555)/dbname?tls=skip-verify&autocommit=true user:password@/dbname?sql_mode=TRADITIONAL user:password@tcp([de:ad:be:ef::ca:fe]:80)/dbname?timeout=90s&collation=utf8mb4_unicode_ci id:password@tcp(your-amazonaws-uri.com:3306)/dbname user:password@unix(/cloudsql/project-id:region-name:instance-name)/dbname user:password@tcp/dbname?charset=utf8mb4,utf8&sys_var=esc%40ped user:password@/dbname user:password@/ ``` -------------------------------- ### DSN Example Source: https://github.com/notaryproject/notary/blob/master/vendor/github.com/mattn/go-sqlite3/README.md An example of a Data Source Name (DSN) string for connecting to an SQLite database, including cache and mode configurations. ```sql file:test.db?cache=shared&mode=memory ``` -------------------------------- ### Install Go Source: https://github.com/notaryproject/notary/blob/master/vendor/github.com/bugsnag/bugsnag-go/CONTRIBUTING.md Installs the Go programming language using Homebrew, enabling cross-compilation. ```shell brew install go --cross-compile-all ``` -------------------------------- ### Start Notary Service with Docker Compose Source: https://github.com/notaryproject/notary/blob/master/docs/running_a_service.md Clones the Notary repository, navigates into the directory, and starts the Notary server, signer, and MySQL database using Docker Compose. This is the quickest way to set up a Notary service for testing and development. ```plain git clone https://github.com/theupdateframework/notary.git cd notary docker-compose up ``` -------------------------------- ### Viper Get Methods Source: https://github.com/notaryproject/notary/blob/master/vendor/github.com/spf13/viper/README.md Illustrates various methods provided by Viper to retrieve configuration values based on their expected data types. It also highlights the `IsSet` method for checking key existence and the behavior of Get functions when a key is not found. ```go viper.GetString("logfile") // case-insensitive Setting & Getting if viper.GetBool("verbose") { fmt.Println("verbose enabled") } ``` -------------------------------- ### Notary Signer Configuration File Example Source: https://github.com/notaryproject/notary/blob/master/docs/reference/signer-config.md Provides a full example of a Notary signer configuration file, demonstrating the structure and key sections like server, logging, storage, and reporting. ```json { "server": { "grpc_addr": ":7899", "tls_cert_file": "./fixtures/notary-signer.crt", "tls_key_file": "./fixtures/notary-signer.key", "client_ca_file": "./fixtures/notary-server.crt" }, "logging": { "level": 2 }, "storage": { "backend": "mysql", "db_url": "user:pass@tcp(notarymysql:3306)/databasename?parseTime=true", "default_alias": "passwordalias1" }, "reporting": { "bugsnag": { "api_key": "c9d60ae4c7e70c4b6c4ebd3e8056d2b8", "release_stage": "production" } } } ``` -------------------------------- ### Notary Client Configuration File Example Source: https://github.com/notaryproject/notary/blob/master/docs/reference/client-config.md An example of a complete Notary client configuration file, demonstrating the structure and common settings for trust directory, remote server connection details, and trust pinning. ```json { "trust_dir" : "~/.docker/trust", "remote_server": { "url": "https://my-notary-server.my-private-registry.com", "root_ca": "./fixtures/root-ca.crt", "tls_client_cert": "./fixtures/secure.example.com.crt", "tls_client_key": "./fixtures/secure.example.com.key" }, "trust_pinning": { "certs": { "docker.com/notary": ["49cf5c6404a35fa41d5a5aa2ce539dfee0d7a2176d0da488914a38603b1f4292"] } } } ``` -------------------------------- ### Example Notary Server Configuration File Source: https://github.com/notaryproject/notary/blob/master/docs/running_a_service.md An example JSON configuration file for the Notary server. This file specifies settings for the server's HTTP address, TLS certificates, trust service details, and database storage. It serves as a base configuration that can be overridden by environment variables. ```json { "server": { "http_addr": ":4443", "tls_key_file": "./server.key", "tls_cert_file": "./server.crt" }, "trust_service": { "type": "remote", "hostname": "notarysigner", "port": "7899", "tls_ca_file": "./root-ca.crt", "key_algorithm": "ecdsa", "tls_client_cert": "./notary-server.crt", "tls_client_key": "./notary-server.key" }, "storage": { "backend": "mysql", "db_url": "server@tcp(mysql:3306)/notaryserver?parseTime=True" } } ``` -------------------------------- ### Full Example: Simple Mux Server Source: https://github.com/notaryproject/notary/blob/master/vendor/github.com/gorilla/mux/README.md Provides 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)) } ``` -------------------------------- ### Install and Use YAML Package in Go Source: https://github.com/notaryproject/notary/blob/master/vendor/gopkg.in/yaml.v2/README.md Instructions for installing the yaml.v2 package in Go using go get and provides an example of unmarshalling and marshalling YAML data into Go structs and maps. ```Go go get gopkg.in/yaml.v2 ``` ```Go package main import ( "fmt" "log" "gopkg.in/yaml.v2" ) 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)) } ``` -------------------------------- ### Between Example (Optional Args) Source: https://github.com/notaryproject/notary/blob/master/vendor/gopkg.in/rethinkdb/rethinkdb-go.v6/README.md Shows how to use the Between function with optional arguments, specifying an index and boundary conditions for the range query. ```go r.DB("database").Table("table").Between(1, 10, r.BetweenOpts{ Index: "num", RightBound: "closed", }).Run(session) ``` -------------------------------- ### Basic Example: Hello World Source: https://github.com/notaryproject/notary/blob/master/vendor/gopkg.in/rethinkdb/rethinkdb-go.v6/README.md Demonstrates a basic connection to RethinkDB and executing a simple query to print 'Hello World'. It shows how to establish a session, run an expression, and retrieve the result. ```go package rethinkdb_test import ( "fmt" "log" r "gopkg.in/rethinkdb/rethinkdb-go.v6" ) func Example() { session, err := r.Connect(r.ConnectOpts{ Address: url, // endpoint without http }) if err != nil { log.Fatalln(err) } res, err := r.Expr("Hello World").Run(session) if err != nil { log.Fatalln(err) } var response string err = res.One(&response) if err != nil { log.Fatalln(err) } fmt.Println(response) // Output: // Hello World } ``` -------------------------------- ### User Authentication Setup Source: https://github.com/notaryproject/notary/blob/master/vendor/gopkg.in/rethinkdb/rethinkdb-go.v6/README.md Demonstrates setting up user authentication by creating a user in the 'users' system table and granting permissions, then using username and password in `ConnectOpts`. ```go err := r.DB("rethinkdb").Table("users").Insert(map[string]string{ "id": "john", "password": "p455w0rd", }).Exec(session) ... err = r.DB("blog").Table("posts").Grant("john", map[string]bool{ "read": true, "write": true, }).Exec(session) ... session, err := r.Connect(r.ConnectOpts{ Address: "localhost:28015", Database: "blog", Username: "john", Password: "p455w0rd", }) ``` -------------------------------- ### Install Bugsnag Notifier for Golang Source: https://github.com/notaryproject/notary/blob/master/vendor/github.com/bugsnag/bugsnag-go/README.md This command installs the Bugsnag Notifier library for Golang using the go get command. Ensure you have Go installed and configured correctly. ```shell go get github.com/bugsnag/bugsnag-go ``` -------------------------------- ### Cobra Application Initialization and Flags Source: https://github.com/notaryproject/notary/blob/master/vendor/github.com/spf13/cobra/user_guide.md Sets up the root command, initializes configuration using Viper, defines persistent flags, binds flags to Viper, and adds subcommands. ```go package cmd import ( "fmt" "os" "github.com/spf13/cobra" "github.com/spf13/viper" ) var ( // Used for flags. cfgFile string userLicense string rootCmd = &cobra.Command{ Use: "cobra-cli", Short: "A generator for Cobra based Applications", Long: `Cobra is a CLI library for Go that empowers applications. This application is a tool to generate the needed files to quickly create a Cobra application.`, } ) // Execute executes the root command. func Execute() error { return rootCmd.Execute() } func init() { cobra.OnInitialize(initConfig) rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)") rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution") rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project") rootCmd.PersistentFlags().Bool("viper", true, "use Viper for configuration") vper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author")) vper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper")) vper.SetDefault("author", "NAME HERE ") vper.SetDefault("license", "apache") rootCmd.AddCommand(addCmd) rootCmd.AddCommand(initCmd) } func initConfig() { if cfgFile != "" { // Use config file from the flag. vper.SetConfigFile(cfgFile) } else { // Find home directory. home, err := os.UserHomeDir() cobra.CheckErr(err) // Search config in home directory with name ".cobra" (without extension). vper.AddConfigPath(home) vper.SetConfigType("yaml") vper.SetConfigName(".cobra") } vper.AutomaticEnv() if err := vper.ReadInConfig(); err == nil { fmt.Println("Using config file:", vper.ConfigFileUsed()) } } ``` -------------------------------- ### Building Notary CLI Source: https://github.com/notaryproject/notary/blob/master/README.md Instructions for building the Notary CLI client from source using Go. It includes setting the GOPATH, enabling Go modules, and installing the notary binary with optional PKCS11 support for YubiKey. ```go export GO111MODULE=on go get github.com/theupdateframework/notary # build with pkcs11 support by default to support yubikey go install -tags pkcs11 github.com/theupdateframework/notary/cmd/notary notary ``` -------------------------------- ### Install Go Terminal Package Source: https://github.com/notaryproject/notary/blob/master/vendor/golang.org/x/term/README.md Installs the Go terminal package using the go get command. This is the recommended method for obtaining the latest version of the package. ```bash go get -u golang.org/x/term ``` -------------------------------- ### Serving Static Files with Gorilla Mux Source: https://github.com/notaryproject/notary/blob/master/vendor/github.com/gorilla/mux/README.md Provides a complete example of how to serve static files from a directory using `http.FileServer` and `http.StripPrefix` with Gorilla Mux. ```go package main import ( "flag" "log" "net/http" "time" "github.com/gorilla/mux" ) func main() { var dir string flag.StringVar(&dir, "dir", ".", "the directory to serve files from. Defaults to the current dir") flag.Parse() r := mux.NewRouter() // This will serve files under http://localhost:8000/static/ r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(dir)))) srv := &http.Server{ Handler: r, Addr: "127.0.0.1:8000", // Good practice: enforce timeouts for servers you create! WriteTimeout: 15 * time.Second, ReadTimeout: 15 * time.Second, } log.Fatal(srv.ListenAndServe()) } ``` -------------------------------- ### Get Document Example Source: https://github.com/notaryproject/notary/blob/master/vendor/gopkg.in/rethinkdb/rethinkdb-go.v6/README.md Illustrates how to retrieve a specific document from a RethinkDB table by its ID using the Go driver. ```go r.DB("database").Table("table").Get("GUID").Run(session) ``` -------------------------------- ### Get Go Version Source: https://github.com/notaryproject/notary/blob/master/vendor/github.com/gorilla/mux/ISSUE_TEMPLATE.md This snippet shows how to retrieve the currently installed Go version, which is crucial for ensuring compatibility and diagnosing environment-specific issues. ```bash go version ``` -------------------------------- ### Basic Connection Setup Source: https://github.com/notaryproject/notary/blob/master/vendor/gopkg.in/rethinkdb/rethinkdb-go.v6/README.md Establishes a basic connection to RethinkDB. The `Connect` function takes `ConnectOpts` to specify connection parameters like the address. ```go func ExampleConnect() { var err error session, err = r.Connect(r.ConnectOpts{ Address: url, }) if err != nil { log.Fatalln(err.Error()) } } ``` -------------------------------- ### Clearing All Pending Changes in Notary Source: https://github.com/notaryproject/notary/blob/master/docs/getting_started.md Explains how to use the `reset` subcommand with the `--all` flag to remove all pending changes for a specified GUN (Globally Unique Name) in Notary. ```shell notary -d ~/.docker/trust reset --all ``` -------------------------------- ### New Build System - Show Commands Source: https://github.com/notaryproject/notary/blob/master/vendor/golang.org/x/sys/unix/README.md Command to display the build commands that will be executed by mkall.sh without actually running them. Useful for debugging the new build system. ```bash mkall.sh -n ``` -------------------------------- ### Re-install go-sqlite3 Source: https://github.com/notaryproject/notary/blob/master/vendor/github.com/mattn/go-sqlite3/README.md Provides a solution for 'go get' compilation errors, specifically when 'gcc' throws an 'internal compiler error'. It suggests removing the existing repository and using 'go install'. ```bash go install github.com/mattn/go-sqlite3 ``` -------------------------------- ### Walking Registered Routes (Go) Source: https://github.com/notaryproject/notary/blob/master/vendor/github.com/gorilla/mux/README.md Provides an example of using the `Walk` function to iterate over all registered routes in a `mux.Router`. It demonstrates how to retrieve details like path templates, regexps, and methods for each route. ```go package main import ( "fmt" "net/http" "strings" "github.com/gorilla/mux" ) func handler(w http.ResponseWriter, r *http.Request) { return } func main() { r := mux.NewRouter() r.HandleFunc("/", handler) r.HandleFunc("/products", handler).Methods("POST") r.HandleFunc("/articles", handler).Methods("GET") r.HandleFunc("/articles/{id}", handler).Methods("GET", "PUT") r.HandleFunc("/authors", handler).Queries("surname", "{surname}") err := r.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error { pathTemplate, err := route.GetPathTemplate() if err == nil { fmt.Println("ROUTE:", pathTemplate) } pathRegexp, err := route.GetPathRegexp() if err == nil { fmt.Println("Path regexp:", pathRegexp) } queriesTemplates, err := route.GetQueriesTemplates() if err == nil { fmt.Println("Queries templates:", strings.Join(queriesTemplates, ",")) } queriesRegexps, err := route.GetQueriesRegexp() if err == nil { fmt.Println("Queries regexps:", strings.Join(queriesRegexps, ",")) } methods, err := route.GetMethods() if err == nil { fmt.Println("Methods:", strings.Join(methods, ",")) } fmt.Println() return nil }) if err != nil { fmt.Println(err) } http.Handle("/", r) } ``` -------------------------------- ### Basic Usage Source: https://github.com/notaryproject/notary/blob/master/vendor/github.com/go-sql-driver/mysql/README.md Demonstrates how to open a database connection using the Go-MySQL-Driver with the database/sql package. It requires importing the driver and providing a DSN. ```go import "database/sql" import _ "github.com/go-sql-driver/mysql" db, err := sql.Open("mysql", "user:password@/dbname") ``` -------------------------------- ### Resetting Individual Changes in Notary Source: https://github.com/notaryproject/notary/blob/master/docs/getting_started.md Demonstrates how to remove specific unpublished changes from a Notary changelist using the `reset` command with the `-n` flag to specify the change index. It also shows how indices are updated after removal. ```shell $ notary -d ~/.docker/trust status docker.io/library/alpine Unpublished changes for docker.io/library/alpine: # ACTION SCOPE TYPE PATH \- ------ ----- ---- ---- 0 delete targets target 2.6 1 create targets target 3.0 $ notary -d ~/.docker/trust reset docker.io/library/alpine -n 0 $ notary -d ~/.docker/trust status docker.io/library/alpine Unpublished changes for docker.io/library/alpine: # ACTION SCOPE TYPE PATH \- ------ ----- ---- ---- 0 create targets target 3.0 ``` -------------------------------- ### Creating and Configuring Multiple Vipers Source: https://github.com/notaryproject/notary/blob/master/vendor/github.com/spf13/viper/README.md Demonstrates how to instantiate multiple Viper objects, each with its own set of default configurations. This allows for managing distinct configuration sets within a single application. ```go x := viper.New() y := viper.New() x.SetDefault("ContentDir", "content") y.SetDefault("ContentDir", "foobar") ``` -------------------------------- ### Viper Environment Variable Handling Source: https://github.com/notaryproject/notary/blob/master/vendor/github.com/spf13/viper/README.md Demonstrates how Viper interacts with environment variables, including setting prefixes, binding keys to environment variables, and automatic environment variable detection. It highlights case sensitivity and how prefixes are applied. ```go import ( "os" "github.com/spf13/viper" ) // Set environment variable prefix vpr := viper.New() vpr.SetEnvPrefix("spf") // will be uppercased automatically // Bind a key to an environment variable vpr.BindEnv("id") // Set the environment variable (typically done outside the app) os.Setenv("SPF_ID", "13") // Get the value, which will be read from the environment variable id := vpr.Get("id") // id will be "13" ``` -------------------------------- ### Initialize and Use SoftHSM Source: https://github.com/notaryproject/notary/blob/master/vendor/github.com/miekg/pkcs11/README.md Demonstrates how to initialize a SoftHSM token and then use the pkcs11 library to connect to it. Requires SoftHSM to be installed and configured. ```go p := pkcs11.New("/usr/lib/softhsm/libsofthsm.so") ``` -------------------------------- ### Building URLs with Host and Query Variables (Go) Source: https://github.com/notaryproject/notary/blob/master/vendor/github.com/gorilla/mux/README.md Shows how to build complete URLs including host and query parameters from a named route. This allows for dynamic generation of URLs with multiple components. ```go r := mux.NewRouter() r.Host("{subdomain}.example.com"). Path("/articles/{category}/{id:[0-9]+}"). Queries("filter", "{filter}"). HandlerFunc(ArticleHandler). Name("article") url, err := r.Get("article").URL("subdomain", "news", "category", "technology", "id", "42", "filter", "gorilla") // url.String() will be "http://news.example.com/articles/technology/42?filter=gorilla" ``` -------------------------------- ### Basic Panic Wrap Example Source: https://github.com/notaryproject/notary/blob/master/vendor/github.com/bugsnag/panicwrap/README.md Demonstrates the basic usage of panicwrap. It sets up a wrapper that re-executes the program and calls a handler function when a panic is detected in the child process. The handler function receives the panic output. ```go package main import ( "fmt" "github.com/mitchellh/panicwrap" "os" ) func main() { exitStatus, err := panicwrap.BasicWrap(panicHandler) if err != nil { // Something went wrong setting up the panic wrapper. Unlikely, // but possible. panic(err) } // If exitStatus >= 0, then we're the parent process and the panicwrap // re-executed ourselves and completed. Just exit with the proper status. if exitStatus >= 0 { os.Exit(exitStatus) } // Otherwise, exitStatus < 0 means we're the child. Continue executing as // normal... // Let's say we panic panic("oh shucks") } func panicHandler(output string) { // output contains the full output (including stack traces) of the // panic. Put it in a file or something. fmt.Printf("The child panicked:\n\n%s\n", output) os.Exit(1) } ``` -------------------------------- ### Build Go with Features Source: https://github.com/notaryproject/notary/blob/master/vendor/github.com/mattn/go-sqlite3/README.md Demonstrates how to build the Go library with specific features enabled using build tags. Multiple features can be included by space-delimiting them. ```bash go build --tags "" ``` ```bash go build --tags "icu json1 fts5 secure_delete" ``` -------------------------------- ### Install Homebrew Source: https://github.com/notaryproject/notary/blob/master/vendor/github.com/bugsnag/bugsnag-go/CONTRIBUTING.md Installs Homebrew, a package manager for macOS, using a Ruby script. ```shell ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)" ``` -------------------------------- ### Old Build System - Show Commands Source: https://github.com/notaryproject/notary/blob/master/vendor/golang.org/x/sys/unix/README.md Command to display the build commands that will be executed by mkall.sh without actually running them. Useful for debugging the old build system. ```bash mkall.sh -n ``` -------------------------------- ### Example JSON Log Output Source: https://github.com/notaryproject/notary/blob/master/docs/running_a_service.md Example of JSON-formatted log output from the Notary server, as configured by the `-logf=json` flag. ```json {"level":"info","msg":"Version: 0.2, Git commit: 619f8cf","time":"2016-02-25T00:53:59Z"} {"level":"info","msg":"Using local signing service, which requires ED25519. Ignoring all other trust_service parameters, including keyAlgorithm","time":"2016-02-25T00:53:59Z"} {"level":"info","msg":"Using memory backend","time":"2016-02-25T00:53:59Z"} {"level":"info","msg":"Starting Server","time":"2016-02-25T00:53:59Z"} {"level":"info","msg":"Enabling TLS","time":"2016-02-25T00:53:59Z"} {"level":"info","msg":"Starting on :4443","time":"2016-02-25T00:53:59Z"} ``` -------------------------------- ### Basic Cobra Application Structure Source: https://github.com/notaryproject/notary/blob/master/vendor/github.com/spf13/cobra/user_guide.md Illustrates a typical directory structure for a Cobra-based application, highlighting the placement of command files and the main entry point. ```text ▾ appName/ ▾ cmd/ add.go your.go commands.go here.go main.go ``` -------------------------------- ### Run Registry with Version Check Source: https://github.com/notaryproject/notary/blob/master/vendor/github.com/docker/distribution/BUILDING.md Executes the registry binary to check its version. This command assumes the binary is located in the `$GOPATH/bin` directory. ```bash $GOPATH/bin/registry --version ``` -------------------------------- ### Install Cobra CLI Generator Source: https://github.com/notaryproject/notary/blob/master/vendor/github.com/spf13/cobra/README.md Installs the cobra-cli tool, used for scaffolding new Cobra-based applications. ```bash go install github.com/spf13/cobra-cli@latest ``` -------------------------------- ### Install Cobra Library Source: https://github.com/notaryproject/notary/blob/master/vendor/github.com/spf13/cobra/README.md Installs the latest version of the Cobra library using the Go package manager. ```go go get -u github.com/spf13/cobra@latest ```