### Install Afero Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/spf13/afero/README.md Use `go get` to install the latest version of the Afero library. ```bash $ go get github.com/spf13/afero ``` -------------------------------- ### Install locafero Library Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/sagikazarmark/locafero/README.md Use 'go get' to install the locafero library. This command fetches and installs the specified package. ```shell go get github.com/sagikazarmark/locafero ``` -------------------------------- ### Install Zerolog Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/rs/zerolog/README.md Install the zerolog logger package using go get. ```bash go get -u github.com/rs/zerolog/log ``` -------------------------------- ### Install Bodytype Plugin Source: https://github.com/exoscale/cli/blob/master/vendor/gopkg.in/h2non/gentleman.v2/plugins/bodytype/README.md Install the bodytype plugin using go get. ```bash go get -u gopkg.in/h2non/gentleman.v2/plugins/bodytype ``` -------------------------------- ### Install Gentleman Multipart Plugin Source: https://github.com/exoscale/cli/blob/master/vendor/gopkg.in/h2non/gentleman.v2/plugins/multipart/README.md Install the multipart plugin using go get. ```bash go get -u gopkg.in/h2non/gentleman.v2/plugins/multipart ``` -------------------------------- ### Create and Manage Exoscale Instance Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/exoscale/egoscale/v3/README.md Example demonstrating how to create a new Exoscale instance, wait for its creation to complete, and then retrieve its details. It shows credential setup, client initialization, and resource creation with specific parameters. ```golang package main import ( "context" "log" "github.com/davecgh/go-spew/spew" v3 "github.com/exoscale/egoscale/v3" "github.com/exoscale/egoscale/v3/credentials" ) func main() { creds := credentials.NewEnvCredentials() // OR creds = credentials.NewStaticCredentials("EXOxxx..", "...") client, err := v3.NewClient(creds) if err != nil { log.Fatal(err) } ctx := context.Background() op, err := client.CreateInstance(ctx, v3.CreateInstanceRequest{ Name: "egoscale-v3", DiskSize: 50, // Ubuntu 24.04 LTS Template: &v3.Template{ID: v3.UUID("cbd89eb1-c66c-4637-9483-904d7e36c318")}, // Medium type InstanceType: &v3.InstanceType{ID: v3.UUID("b6e9d1e8-89fc-4db3-aaa4-9b4c5b1d0844")}, }) if err != nil { log.Fatal(err) } op, err = client.Wait(ctx, op, v3.OperationStateSuccess) if err != nil { log.Fatal(err) } instance, err := client.GetInstance(ctx, op.Reference.ID) if err != nil { log.Fatal(err) } spew.Dump(instance) } ``` -------------------------------- ### Install Gentleman Context Package Source: https://github.com/exoscale/cli/blob/master/vendor/gopkg.in/h2non/gentleman.v2/context/README.md Use go get to install the gentleman/context package. This command fetches and installs the latest version. ```bash go get -u gopkg.in/h2non/gentleman.v2/context ``` -------------------------------- ### Install slog-shim Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/sagikazarmark/slog-shim/README.md Install the slog-shim package using go get. ```shell go get github.com/sagikazarmark/slog-shim ``` -------------------------------- ### Install gojsonschema Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/xeipuuv/gojsonschema/README.md Use 'go get' to install the gojsonschema library and its dependencies. ```go go get github.com/xeipuuv/gojsonschema ``` -------------------------------- ### Install UUID Package Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/google/uuid/README.md Install the UUID package using the go get command. ```sh go get github.com/google/uuid ``` -------------------------------- ### Install Gentleman Middleware Source: https://github.com/exoscale/cli/blob/master/vendor/gopkg.in/h2non/gentleman.v2/middleware/README.md Installs the gentleman.v2/middleware package using go get. ```bash go get -u gopkg.in/h2non/gentleman.v2/middleware ``` -------------------------------- ### Install go-isatty Package Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/mattn/go-isatty/README.md This command installs the go-isatty package using the go get command. ```bash go get github.com/mattn/go-isatty ``` -------------------------------- ### Install go-urn Package Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/leodido/go-urn/README.md Install the go-urn package using the go get command. This is the initial step before using the library in your Go projects. ```bash go get github.com/leodido/go-urn ``` -------------------------------- ### Install Chroma Command-line Tool Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/alecthomas/chroma/README.md Installs the Chroma command-line interface using go get. ```sh go get -u github.com/alecthomas/chroma/cmd/chroma ``` -------------------------------- ### Install Viper Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/spf13/viper/README.md Install the Viper library using go get. Viper uses Go Modules for dependency management. ```shell go get github.com/spf13/viper ``` -------------------------------- ### Install Gentleman URL Plugin Source: https://github.com/exoscale/cli/blob/master/vendor/gopkg.in/h2non/gentleman.v2/plugins/url/README.md Install the Gentleman URL plugin using go get. ```bash go get -u gopkg.in/h2non/gentleman.v2/plugins/url ``` -------------------------------- ### Install Gentleman Headers Plugin Source: https://github.com/exoscale/cli/blob/master/vendor/gopkg.in/h2non/gentleman.v2/plugins/headers/README.md Use 'go get' to install the headers plugin. This command fetches and installs the specified package and its dependencies. ```bash go get -u gopkg.in/h2non/gentleman.v2/plugins/headers ``` -------------------------------- ### Install Gentleman Mux Package Source: https://github.com/exoscale/cli/blob/master/vendor/gopkg.in/h2non/gentleman.v2/mux/README.md Install the gentleman/mux package using go get. ```bash go get -u gopkg.in/h2non/gentleman.v2/mux ``` -------------------------------- ### Install Go Locales Package Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/go-playground/locales/README.md Use 'go get' to install the go-playground/locales package. ```shell go get github.com/go-playground/locales ``` -------------------------------- ### Install Mimetype Go Package Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/gabriel-vasile/mimetype/README.md Use 'go get' to install the Mimetype package. This command fetches and installs the package and its dependencies. ```bash go get github.com/gabriel-vasile/mimetype ``` -------------------------------- ### Install INI Package for Go Source: https://github.com/exoscale/cli/blob/master/vendor/gopkg.in/ini.v1/README.md Install the go-ini package using the go get command. Use the -u flag for future updates. ```sh go get gopkg.in/ini.v1 ``` -------------------------------- ### Install go-colorable Package Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/mattn/go-colorable/README.md Install the go-colorable package using the go get command. This is a prerequisite for using the package in your Go projects. ```bash $ go get github.com/mattn/go-colorable ``` -------------------------------- ### Install CamelCase Package Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/fatih/camelcase/README.md Install the CamelCase package using the go get command. ```bash go get github.com/fatih/camelcase ``` -------------------------------- ### Install Validator Package Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/go-playground/validator/v10/README.md Install the validator package using go get. Then import it into your Go code. ```go go get github.com/go-playground/validator/v10 ``` ```go import "github.com/go-playground/validator/v10" ``` -------------------------------- ### Install Gentleman Plugin Package Source: https://github.com/exoscale/cli/blob/master/vendor/gopkg.in/h2non/gentleman.v2/plugin/README.md Install the Gentleman plugin package using go get. ```bash go get -u gopkg.in/h2non/gentleman.v2/plugin ``` -------------------------------- ### Install Cobra Library Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/spf13/cobra/README.md Use 'go get' to install the latest version of the Cobra library and its dependencies. ```bash go get -u github.com/spf13/cobra ``` -------------------------------- ### Go: JSON Pointer Usage Example Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/xeipuuv/gojsonpointer/README.md Demonstrates creating a JSON Pointer, setting a new value, getting a value, and deleting a value from a JSON document. Requires the 'encoding/json' and 'fmt' packages. ```go jsonText := `{ "name": "Bobby B", "occupation": { "title" : "King", "years" : 15, "heir" : "Joffrey B" } }` var jsonDocument map[string]interface{} json.Unmarshal([]byte(jsonText), &jsonDocument) //create a JSON pointer pointerString := "/occupation/title" pointer, _ := NewJsonPointer(pointerString) //SET a new value for the "title" in the document pointer.Set(jsonDocument, "Supreme Leader of Westeros") //GET the new "title" from the document title, _, _ := pointer.Get(jsonDocument) fmt.Println(title) //outputs "Supreme Leader of Westeros" //DELETE the "heir" from the document deletePointer := NewJsonPointer("/occupation/heir") deletePointer.Delete(jsonDocument) b, _ := json.Marshal(jsonDocument) fmt.Println(string(b)) //outputs `{"name":"Bobby B","occupation":{"title":"Supreme Leader of Westeros","years":15}}` ``` -------------------------------- ### Install Universal Translator Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/go-playground/universal-translator/README.md Install the Universal Translator package using go get. ```shell go get github.com/go-playground/universal-translator ``` -------------------------------- ### Install mapstructure Go Library Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/mitchellh/mapstructure/README.md Use 'go get' to install the mapstructure library. This is the standard method for obtaining Go packages. ```bash go get github.com/mitchellh/mapstructure ``` -------------------------------- ### Install openapi-cli-generator 'j' tool Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/exoscale/openapi-cli-generator/shorthand/README.md Command to install the 'j' executable for trying out shorthand format examples. ```sh go get -u github.com/danielgtaylor/openapi-cli-generator/j ``` -------------------------------- ### Default Kingpin Help Output Example Source: https://github.com/exoscale/cli/blob/master/vendor/gopkg.in/alecthomas/kingpin.v3-unstable/README.md Example of the default help message generated by Kingpin for a sample application. ```bash $ go run ./examples/curl/curl.go --help usage: curl [] [ ...] An example implementation of curl. Flags: --help Show help. -t, --timeout=5s Set connection timeout. -H, --headers=HEADER=VALUE Add HTTP headers to the request. Commands: help [...] Show help. get url Retrieve a URL. get file Retrieve a file. post [] POST a resource. ``` -------------------------------- ### Install Gentleman Query Plugin Source: https://github.com/exoscale/cli/blob/master/vendor/gopkg.in/h2non/gentleman.v2/plugins/query/README.md Install the query plugin using the go get command. Ensure you are using the v2 version of gentleman. ```bash go get -u gopkg.in/h2non/gentleman.v2/plugins/query ``` -------------------------------- ### Install uniseg Package Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/rivo/uniseg/README.md Use 'go get' to install the uniseg package. This package has no external dependencies. ```bash go get github.com/rivo/uniseg ``` -------------------------------- ### Run gometalinter on Example Project Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/alecthomas/gometalinter/README.md Executes gometalinter on all Go packages within the 'example' directory. This command will output any detected issues from the installed linters. ```bash $ cd example $ gometalinter ./... ``` -------------------------------- ### Install Egoscale v3 Dependency Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/exoscale/egoscale/v3/README.md Install the egoscale v3 package using go get. ```shell go get "github.com/exoscale/egoscale/v3" ``` -------------------------------- ### Install go.uber.org/atomic Package Source: https://github.com/exoscale/cli/blob/master/vendor/go.uber.org/atomic/README.md Install the latest version of the go.uber.org/atomic package using go get. ```shell $ go get -u go.uber.org/atomic@v1 ``` -------------------------------- ### Install Gentleman Body Plugin Source: https://github.com/exoscale/cli/blob/master/vendor/gopkg.in/h2non/gentleman.v2/plugins/body/README.md Install the body plugin using go get. This command fetches the latest version of the plugin. ```bash go get -u gopkg.in/h2non/gentleman.v2/plugins/body ``` -------------------------------- ### Quick misspell installation Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/client9/misspell/README.md A concise command to download and execute the misspell installation script. ```bash curl -L https://git.io/misspell | bash ``` -------------------------------- ### Complex CLI Application Example Source: https://github.com/exoscale/cli/blob/master/vendor/gopkg.in/alecthomas/kingpin.v3-unstable/README.md Demonstrates a complex CLI application with global flags, subcommands, and per-subcommand flags. This example shows how to define and use these features. ```go package main import ( "os" "strings" "gopkg.in/alecthomas/kingpin.v2" ) var ( app = kingpin.New("chat", "A command-line chat application.") debug = app.Flag("debug", "Enable debug mode.").Bool() serverIP = app.Flag("server", "Server address.").Default("127.0.0.1").IP() register = app.Command("register", "Register a new user.") registerNick = register.Arg("nick", "Nickname for user.").Required().String() registerName = register.Arg("name", "Name of user.").Required().String() post = app.Command("post", "Post a message to a channel.") postImage = post.Flag("image", "Image to post.").File() postChannel = post.Arg("channel", "Channel to post to.").Required().String() postText = post.Arg("text", "Text to post.").Strings() ) func main() { switch kingpin.MustParse(app.Parse(os.Args[1:])) { // Register user case register.FullCommand(): println(*registerNick) // Post message case post.FullCommand(): if *postImage != nil { } text := strings.Join(*postText, " ") println("Post:", text) } } ``` -------------------------------- ### Simple Kingpin Example Source: https://github.com/exoscale/cli/blob/master/vendor/gopkg.in/alecthomas/kingpin.v3-unstable/README.md A basic example demonstrating how to define and parse a boolean flag and a required string argument using Kingpin. ```go var ( verbose = kingpin.Flag("verbose", "Verbose mode.").Short('v').Bool() name = kingpin.Arg("name", "Name of user.").Required().String() ) func main() { kingpin.Parse() fmt.Printf("%v, %s\n", *verbose, *name) } ``` -------------------------------- ### Install strcase Go Package Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/iancoleman/strcase/README.md Command to install the strcase Go package using the go get command. Ensure you are using a compatible Go version. ```bash go get -u github.com/iancoleman/strcase ``` -------------------------------- ### Install All Known Linters Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/alecthomas/gometalinter/README.md Installs all linters that gometalinter is aware of. This command fetches and installs the necessary tools. ```bash $ gometalinter --install ``` -------------------------------- ### Install Gentleman v2 Source: https://github.com/exoscale/cli/blob/master/vendor/gopkg.in/h2non/gentleman.v2/README.md Install the latest stable version of the Gentleman toolkit using Go's package management. ```bash go get -u gopkg.in/h2non/gentleman.v2 ``` -------------------------------- ### Go Example: Basic Cleaning Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/lunixbochs/vtclean/README.md Demonstrates basic cleaning of a string using vtclean.Clean with color disabled. ```go package main import ( "fmt" "github.com/lunixbochs/vtclean" ) func main() { line := vtclean.Clean( "\033[1;32mcolor, " + "curs\033[Aor, " + "backspace\b\b\b\b\b\b\b\b\b\b\b\033[K", false) fmt.Println(line) } ``` -------------------------------- ### Install misspell CLI Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/client9/misspell/README.md Download and install the misspell executable script. The binary is installed as './bin/misspell'. ```bash curl -L -o ./install-misspell.sh https://git.io/misspell sh ./install-misspell.sh ``` -------------------------------- ### Get Configuration Values with Viper Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/spf13/viper/README.md Illustrates how to retrieve configuration values of various types (string, bool, int, etc.) using Viper's Get methods. It also shows how to check for the existence of a key using IsSet. ```go viper.GetString("logfile") // case-insensitive Setting & Getting if viper.GetBool("verbose") { fmt.Println("verbose enabled") } ``` -------------------------------- ### Install Gentleman Utils Package Source: https://github.com/exoscale/cli/blob/master/vendor/gopkg.in/h2non/gentleman.v2/utils/README.md Use this command to install the gentleman/utils package and its dependencies. ```bash go get -u gopkg.in/h2non/gentleman.v2/utils ``` -------------------------------- ### Basic Cookie Management Example Source: https://github.com/exoscale/cli/blob/master/vendor/gopkg.in/h2non/gentleman.v2/plugins/cookies/README.md Demonstrates creating a client, setting a cookie, configuring a cookie jar, and making a request to a test endpoint. ```go package main import ( "fmt" "gopkg.in/h2non/gentleman.v2" "gopkg.in/h2non/gentleman.v2/plugins/cookies" ) func main() { // Create a new client cli := gentleman.New() // Define cookies cli.Use(cookies.Set("foo", "bar")) // Configure cookie jar store cli.Use(cookies.Jar()) // Perform the request res, err := cli.Request().URL("http://httpbin.org/cookies").Send() if err != nil { fmt.Printf("Request error: %s\n", err) return } if !res.Ok { fmt.Printf("Invalid server response: %d\n", res.StatusCode) return } fmt.Printf("Status: %d\n", res.StatusCode) fmt.Printf("Body: %s", res.String()) } ``` -------------------------------- ### Simple CLI Application Example Source: https://github.com/exoscale/cli/blob/master/vendor/gopkg.in/alecthomas/kingpin.v3-unstable/README.md Demonstrates a basic Kingpin application with flags and arguments. Shows how to define boolean, duration, IP address, and integer flags/arguments, and how to parse them. ```go package main import ( "fmt" "gopkg.in/alecthomas/kingpin.v2" ) var ( debug = kingpin.Flag("debug", "Enable debug mode.").Bool() timeout = kingpin.Flag("timeout", "Timeout waiting for ping.").Default("5s").OverrideDefaultFromEnvar("PING_TIMEOUT").Short('t').Duration() ip = kingpin.Arg("ip", "IP address to ping.").Required().IP() count = kingpin.Arg("count", "Number of packets to send").Int() ) func main() { kingpin.Version("0.0.1") kingpin.Parse() fmt.Printf("Would ping: %s with timeout %s and count %d", *ip, *timeout, *count) } ``` -------------------------------- ### Using MemMapFs Backend Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/spf13/afero/README.md Shows how to initialize and use Afero's MemMapFs, an atomic and fully concurrent memory-backed filesystem. It's ideal for mocking and speeding up operations when disk persistence is not required. ```go mm := afero.NewMemMapFs() mm.MkdirAll("src/a", 0755) ``` -------------------------------- ### Make a Simple HTTP Request in Go Source: https://github.com/exoscale/cli/blob/master/vendor/gopkg.in/h2non/gentleman.v2/README.md Demonstrates how to create a new client, set a base URL, define a request path, add headers, and send a request. Handles potential request errors and checks for successful server responses. ```go package main import ( "fmt" "gopkg.in/h2non/gentleman.v2" ) func main() { // Create a new client cli := gentleman.New() // Define base URL cli.URL("http://httpbin.org") // Create a new request based on the current client req := cli.Request() // Define the URL path at request level req.Path("/headers") // Set a new header field req.SetHeader("Client", "gentleman") // Perform the request res, err := req.Send() if err != nil { fmt.Printf("Request error: %s\n", err) return } if !res.Ok { fmt.Printf("Invalid server response: %d\n", res.StatusCode) return } // Reads the whole body and returns it as string fmt.Printf("Body: %s", res.String()) } ``` -------------------------------- ### Basic Select with String Options Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/manifoldco/promptui/README.md Shows how to create a select prompt with a list of string options. The user selects one item from the list. ```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) } ``` -------------------------------- ### Example Usage of Gentleman Query Plugin Source: https://github.com/exoscale/cli/blob/master/vendor/gopkg.in/h2non/gentleman.v2/plugins/query/README.md Demonstrates how to set and delete query parameters for an HTTP request using the gentleman client and its query plugin. This example sets a 'foo' parameter to 'bar' and removes a 'bar' parameter before sending the request. ```go package main import ( "fmt" "gopkg.in/h2non/gentleman.v2" "gopkg.in/h2non/gentleman.v2/plugins/query" "gopkg.in/h2non/gentleman.v2/plugins/url" ) func main() { // Create a new client cli := gentleman.New() // Define the base URL to use cli.Use(url.BaseURL("http://httpbin.org")) cli.Use(url.Path("/get")) // Define a custom query param cli.Use(query.Set("foo", "bar")) // Remove a query param cli.Use(query.Del("bar")) // Perform the request res, err := cli.Request().Send() if err != nil { fmt.Printf("Request error: %s\n", err) return } if !res.Ok { fmt.Printf("Invalid server response: %d\n", res.StatusCode) return } fmt.Printf("Status: %d\n", res.StatusCode) fmt.Printf("Body: %s", res.String()) } ``` -------------------------------- ### Compact Help Template Example Source: https://github.com/exoscale/cli/blob/master/vendor/gopkg.in/alecthomas/kingpin.v3-unstable/README.md Demonstrates how to generate a compact help message for a Kingpin application. This is useful for providing concise usage information to users. ```bash $ go run ./examples/curl/curl.go --help usage: curl [] [ ...] An example implementation of curl. Flags: --help Show help. -t, --timeout=5s Set connection timeout. -H, --headers=HEADER=VALUE Add HTTP headers to the request. Commands: help [...] get [] url file post [] ``` -------------------------------- ### CamelCase Splitting Examples Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/fatih/camelcase/README.md Illustrates various inputs and their expected outputs when splitting camelCase strings. ```text "" => [] "lowercase" => ["lowercase"] "Class" => ["Class"] "MyClass" => ["My", "Class"] "MyC" => ["My", "C"] "HTML" => ["HTML"] "PDFLoader" => ["PDF", "Loader"] "AString" => ["A", "String"] "SimpleXMLParser" => ["Simple", "XML", "Parser"] "vimRPCPlugin" => ["vim", "RPC", "Plugin"] "GL11Version" => ["GL", "11", "Version"] "99Bottles" => ["99", "Bottles"] "May5" => ["May", "5"] "BFG9000" => ["BFG", "9000"] "BöseÜberraschung" => ["Böse", "Überraschung"] "Two spaces" => ["Two", " ", "spaces"] "BadUTF8\xe2\xe2\xa1" => ["BadUTF8\xe2\xe2\xa1"] ``` -------------------------------- ### Using OsFs Backend Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/spf13/afero/README.md Demonstrates the usage of Afero's OsFs backend, which wraps native OS calls. This allows for easy integration with existing OS file operations and provides a clear path for using a mock filesystem during testing. ```go appfs := afero.NewOsFs() appfs.MkdirAll("src/a", 0755) ``` -------------------------------- ### Simple Logging Example Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/rs/zerolog/README.md Demonstrates basic logging with zerolog using the global logger. Logs will be written with UNIX timestamps by default if TimeFieldFormat is set to zerolog.TimeFormatUnix. ```go package main import ( "github.com/rs/zerolog" "github.com/rs/zerolog/log" ) func main() { // UNIX Time is faster and smaller than most timestamps // If you set zerolog.TimeFieldFormat to an empty string, // logs will write with UNIX time zerolog.TimeFieldFormat = zerolog.TimeFormatUnix log.Print("hello world") } // Output: {"time":1516134303,"level":"debug","message":"hello world"} ``` -------------------------------- ### Load Properties from Various Sources in Go Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/magiconair/properties/README.md Demonstrates loading properties from files, maps, strings, URLs, and command-line flags. Includes examples for single and multiple sources. ```go import ( "flag" "github.com/magiconair/properties" ) func main() { // init from a file p := properties.MustLoadFile("${HOME}/config.properties", properties.UTF8) // or multiple files p = properties.MustLoadFiles([]string{ "${HOME}/config.properties", "${HOME}/config-${USER}.properties", }, properties.UTF8, true) // or from a map p = properties.LoadMap(map[string]string{"key": "value", "abc": "def"}) // or from a string p = properties.MustLoadString("key=value\nabc=def") // or from a URL p = properties.MustLoadURL("http://host/path") // or from multiple URLs p = properties.MustLoadURL([]string{ "http://host/config", "http://host/config-${USER}", }, true) // or from flags p.MustFlag(flag.CommandLine) // get values through getters host := p.MustGetString("host") port := p.GetInt("port", 8080) // or through Decode type Config struct { Host string `properties:"host"` Port int `properties:"port,default=9000"` Accept []string `properties:"accept,default=image/png;image;gif"` Timeout time.Duration `properties:"timeout,default=5s"` } var cfg Config if err := p.Decode(&cfg); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Simple Leveled Logging Example Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/rs/zerolog/README.md Demonstrates logging at the 'info' level. Remember to call Msg() or Msgf() at the end of the chain, as forgetting this will prevent the log from being written. ```go package main import ( "github.com/rs/zerolog" "github.com/rs/zerolog/log" ) func main() { zerolog.TimeFieldFormat = zerolog.TimeFormatUnix log.Info().Msg("hello world") } // Output: {"time":1516134303,"level":"info","message":"hello world"} ``` -------------------------------- ### Install Gentleman Cookies Plugin Source: https://github.com/exoscale/cli/blob/master/vendor/gopkg.in/h2non/gentleman.v2/plugins/cookies/README.md Install the gentleman cookies plugin using go get. ```bash go get -u gopkg.in/h2non/gentleman.v2/plugins/cookies ``` -------------------------------- ### Basic Table Creation in Go Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/olekukonko/tablewriter/README.md Demonstrates how to create a basic ASCII table with headers and data using the tablewriter package. The output is rendered directly to standard output. ```go data := [][]string{ []string{"A", "The Good", "500"}, []string{"B", "The Very very Bad Man", "288"}, []string{"C", "The Ugly", "120"}, []string{"D", "The Gopher", "800"}, } table := tablewriter.NewWriter(os.Stdout) table.SetHeader([]string{"Name", "Sign", "Rating"}) for _, v := range data { table.Append(v) } table.Render() // Send output ``` -------------------------------- ### Example of PreRun and PostRun Hooks Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/spf13/cobra/user_guide.md Demonstrates the execution order of PersistentPreRun, PreRun, Run, PostRun, and PersistentPostRun hooks in root and subcommands. Persistent hooks are inherited by children. ```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() } ``` -------------------------------- ### Basic fsnotify Watcher Example Source: https://github.com/exoscale/cli/blob/master/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, add a directory to watch, and block the main goroutine. ```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{}) } ``` -------------------------------- ### CLI Help Output Example Source: https://github.com/exoscale/cli/blob/master/vendor/gopkg.in/alecthomas/kingpin.v3-unstable/README.md Shows the help output for a complex CLI application, including global flags, subcommands, and subcommand-specific flags. This is useful for understanding the structure of the application. ```text $ chat --help usage: chat [] [] [ ...] A command-line chat application. Flags: --help Show help. --debug Enable debug mode. --server=127.0.0.1 Server address. Commands: help [] Show help for a command. register Register a new user. post [] [] Post a message to a channel. $ chat help post usage: chat [] post [] [] Post a message to a channel. Flags: --image=IMAGE Image to post. Args: Channel to post to. [] Text to post. $ chat post --image=~/Downloads/owls.jpg pics ... ``` -------------------------------- ### Generate Markdown Tree for Entire Command Tree (kubectl Example) Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/spf13/cobra/doc/md_docs.md Generates Markdown documentation for an entire command tree, demonstrated with the kubectl command. This creates a file for each command within the specified directory. Requires Kubernetes and Cobra imports. ```go package main import ( "log" "io/ioutil" "os" "k8s.io/kubernetes/pkg/kubectl/cmd" cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" "github.com/spf13/cobra/doc" ) func main() { kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard) err := doc.GenMarkdownTree(kubectl, "./") if err != nil { log.Fatal(err) } } ``` -------------------------------- ### Install and Upgrade Go Properties Library Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/magiconair/properties/README.md Command to install or update the magiconair/properties Go library using the go get command. ```shell $ go get -u github.com/magiconair/properties ``` -------------------------------- ### Basic HTTP Request Logging in Go Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/izumin5210/httplogger/README.md Demonstrates how to configure an http.Client to use httplogger for logging requests and responses to standard output. ```go func main() { client := &http.Client{ TransPort: httplogger.NewRoundTripper(os.Stdout, nil), } if _, err := client.Get("http://example.com"); err != nil { log.Fatal(err) } } ``` ```text [http] --> 2017/08/25 23:35:56 GET / Host: example.com User-Agent: gentleman/2.0.0 [http] <-- 2017/08/25 23:35:56 HTTP/2.0 200 OK (93ms) Cache-Control: max-age=0, private, must-revalidate Content-Type: application/json; charset=utf-8 Date: Sat, 25 Aug 2017 23:35:56 GMT Server: nginx ... ``` -------------------------------- ### Static Noun Completion with ValidArgs Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/spf13/cobra/shell_completions.md Use the `ValidArgs` field on a `cobra.Command` to provide a pre-defined list of completion choices for nouns. This example shows how to set valid arguments for a 'get' command. ```go validArgs []string = { "pod", "node", "service", "replicationcontroller" } cmd := &cobra.Command{ Use: "get [(-o|--output=)json|yaml|template|...] (RESOURCE [NAME] | RESOURCE/NAME ...)", Short: "Display one or many resources", Long: get_long, Example: get_example, Run: func(cmd *cobra.Command, args []string) { cobra.CheckErr(RunGet(f, out, cmd, args)) }, ValidArgs: validArgs, } ``` -------------------------------- ### Exoscale CLI Configuration File Example Source: https://github.com/exoscale/cli/blob/master/README.md This TOML snippet shows the minimum required format for the Exoscale CLI configuration file, including default account and account credentials. ```toml defaultaccount = "account_name" [[accounts]] key = "API_KEY" name = "account_name" secret = "API_SECRET" ``` -------------------------------- ### Kubernetes Bash Completion Function Example Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/spf13/cobra/bash_completions.md This bash function is designed to be used with Cobra's BashCompletionFunction option to provide dynamic completions for kubectl commands. It parses output from 'kubectl get' to suggest resource names. ```bash __kubectl_parse_get() { local kubectl_output out if kubectl_output=$(kubectl get --no-headers "$1" 2>/dev/null); then out=($(echo "${kubectl_output}" | awk '{print $1}')) COMPREPLY=( $( compgen -W "${out[*]}" -- "$cur" ) ) fi } __kubectl_get_resource() { if [[ ${#nouns[@]} -eq 0 ]]; then return 1 fi __kubectl_parse_get ${nouns[${#nouns[@]} -1]} if [[ $? -eq 0 ]]; then return 0 fi } __kubectl_custom_func() { case ${last_command} in kubectl_get | kubectl_describe | kubectl_delete | kubectl_stop) __kubectl_get_resource return ;; *) ;; esac } ``` -------------------------------- ### Gentleman URL Plugin Example Source: https://github.com/exoscale/cli/blob/master/vendor/gopkg.in/h2non/gentleman.v2/plugins/url/README.md Demonstrates how to use the Gentleman URL plugin to set a base URL, define a path with a dynamic parameter, and replace that parameter to perform an HTTP request. ```go package main import ( "fmt" "gopkg.in/h2non/gentleman.v2" "gopkg.in/h2non/gentleman.v2/plugins/url" ) func main() { // Create a new client cli := gentleman.New() // Define the base URL cli.Use(url.BaseURL("http://httpbin.org")) // Define the path with dynamic value cli.Use(url.Path("/:resource")) // Define the path value to be replaced cli.Use(url.Param("resource", "get")) // Perform the request res, err := cli.Request().Send() if err != nil { fmt.Printf("Request error: %s\n", err) return } if !res.Ok { fmt.Printf("Invalid server response: %d\n", res.StatusCode) return } fmt.Printf("Status: %d\n", res.StatusCode) fmt.Printf("Body: %s", res.String()) } ``` -------------------------------- ### Install Kingpin v1 Source: https://github.com/exoscale/cli/blob/master/vendor/gopkg.in/alecthomas/kingpin.v3-unstable/README.md Command to install the older, now deprecated, v1 of the Kingpin library. ```sh $ go get gopkg.in/alecthomas/kingpin.v1 ``` -------------------------------- ### Install Kingpin v2 Source: https://github.com/exoscale/cli/blob/master/vendor/gopkg.in/alecthomas/kingpin.v3-unstable/README.md Command to install the current stable version of the Kingpin library. ```sh $ go get gopkg.in/alecthomas/kingpin.v2 ``` -------------------------------- ### Install and Update gometalinter with Misspell Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/client9/misspell/README.md Installs or updates gometalinter and ensures misspell is included. ```bash go get -u github.com/alecthomas/gometalinter gometalinter --install --update ``` -------------------------------- ### Install stripansi Package Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/acarl005/stripansi/README.md Use this command to install the stripansi package for your Go project. ```sh $ go get -u github.com/acarl005/stripansi ``` -------------------------------- ### ToString Examples Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/spf13/cast/README.md Demonstrates converting various types to strings using the ToString function. Handles different input types including strings, numbers, byte slices, and nil. ```Go cast.ToString("mayonegg") // "mayonegg" cast.ToString(8) // "8" cast.ToString(8.31) // "8.31" cast.ToString([]byte("one time")) // "one time" cast.ToString(nil) // "" ``` ```Go var foo interface{} = "one more time" cast.ToString(foo) // "one more time" ``` -------------------------------- ### Update Gometalinter and Install Linters Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/alecthomas/gometalinter/CONTRIBUTING.md Update gometalinter to the latest version and install all its vendored linters. ```bash go get -u github.com/alecthomas/gometalinter gometalinter --install ``` -------------------------------- ### Install Latest Stable Release Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/alecthomas/gometalinter/README.md Installs the latest stable release of gometalinter using a curl command. ```bash curl https://git.io/vp6lP | sh ``` -------------------------------- ### Install revgrep for Filtering Issues Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/alecthomas/gometalinter/README.md Install the revgrep tool to filter gometalinter output based on git references. ```bash go get -u github.com/bradleyfalzon/revgrep/... ``` -------------------------------- ### Alternative using 'jo' CLI Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/exoscale/openapi-cli-generator/shorthand/README.md Shows how the same structured data can be generated using the 'jo' CLI tool. ```sh $ jo -p foo=$(jo -p bar=$(jo -a $(jo baz=1 hello=world))) | my-cli do-something ``` -------------------------------- ### Calling Afero Utilities Directly Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/spf13/afero/README.md Demonstrates how to call Afero utility functions by passing the filesystem as the first argument. This approach is useful when you need to operate on a specific filesystem instance. ```go fs := new(afero.MemMapFs) f, err := afero.TempFile(fs,"", "ioutil-test") ``` -------------------------------- ### Install misspell using Go Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/client9/misspell/README.md Install the misspell tool using the Go package manager. The executable will be placed in your GOPATH. ```bash go get -u github.com/client9/misspell/cmd/misspell ``` -------------------------------- ### Example Log Message Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/rs/zerolog/internal/cbor/README.md This is an example of a log message used for size comparison, containing an integer, timestamp, and string field. ```json {"level":"error","Fault":41650,"time":"2018-04-01T15:18:19-07:00","message":"Some Message"} ``` -------------------------------- ### Install and Use Crypt CLI for Remote Config Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/spf13/viper/README.md Commands to install the crypt CLI and set/get configuration values in a key/value store. ```bash $ go get github.com/bketelsen/crypt/bin/crypt $ crypt set -plaintext /config/hugo.json /Users/hugo/settings/config.json ``` ```bash $ crypt get -plaintext /config/hugo.json ``` -------------------------------- ### Install tomll CLI Tool Source: https://github.com/exoscale/cli/blob/master/vendor/github.com/pelletier/go-toml/README.md Installs the 'tomll' command-line tool, which is used for linting TOML files. This command should be run in your terminal. ```bash go install github.com/pelletier/go-toml/cmd/tomll tomll --help ```