### Install xid Package Source: https://github.com/stripe/smokescreen/blob/master/vendor/github.com/rs/xid/README.md Use 'go get' to install the xid package. This command fetches and installs the package and its dependencies. ```go go get github.com/rs/xid ``` -------------------------------- ### Greeter CLI App Example Source: https://github.com/stripe/smokescreen/blob/master/vendor/gopkg.in/urfave/cli.v1/README.md A simple greeter application that prints 'Hello friend!'. This example shows how to set up a basic app with a name, usage, and a custom action. ```go package main import ( "fmt" "os" "github.com/urfave/cli" ) func main() { app := cli.NewApp() app.Name = "greet" app.Usage = "fight the loneliness!" app.Action = func(c *cli.Context) error { fmt.Println("Hello friend!") return nil } app.Run(os.Args) } ``` -------------------------------- ### Install urfave/cli Source: https://github.com/stripe/smokescreen/blob/master/vendor/gopkg.in/urfave/cli.v1/README.md Install the urfave/cli package using go get. Ensure your GOPATH/bin is in your PATH. ```bash go get github.com/urfave/cli ``` ```bash export PATH=$PATH:$GOPATH/bin ``` -------------------------------- ### Install yaml.v3 Package Source: https://github.com/stripe/smokescreen/blob/master/vendor/gopkg.in/yaml.v3/README.md Install the yaml.v3 package using the go get command. ```bash go get gopkg.in/yaml.v3 ``` -------------------------------- ### Initialize Procfs and Get Stats Source: https://github.com/stripe/smokescreen/blob/master/vendor/github.com/prometheus/procfs/README.md Initializes the proc filesystem and retrieves CPU statistics. Use this to start gathering metrics from /proc. ```go fs, err := procfs.NewFS("/proc") stats, err := fs.Stat() ``` -------------------------------- ### Full urfave/cli API Example in Go Source: https://github.com/stripe/smokescreen/blob/master/vendor/gopkg.in/urfave/cli.v1/README.md This example showcases a fully functional, albeit contrived, application demonstrating the extensive API of urfave/cli. It includes custom help templates, flag configurations, command definitions with subcommands, and various lifecycle hooks like Before, After, and Action. ```go package main import ( "errors" "flag" "fmt" "io" "io/ioutil" "os" "time" "github.com/urfave/cli" ) func init() { cli.AppHelpTemplate += "\nCUSTOMIZED: you bet ur muffins\n" cli.CommandHelpTemplate += "\nYMMV\n" cli.SubcommandHelpTemplate += "\nor something\n" cli.HelpFlag = cli.BoolFlag{Name: "halp"} cli.BashCompletionFlag = cli.BoolFlag{Name: "compgen", Hidden: true} cli.VersionFlag = cli.BoolFlag{Name: "print-version, V"} cli.HelpPrinter = func(w io.Writer, templ string, data interface{}) { fmt.Fprintf(w, "best of luck to you\n") } cli.VersionPrinter = func(c *cli.Context) { fmt.Fprintf(c.App.Writer, "version=%s\n", c.App.Version) } cli.OsExiter = func(c int) { fmt.Fprintf(cli.ErrWriter, "refusing to exit %d\n", c) } cli.ErrWriter = ioutil.Discard cli.FlagStringer = func(fl cli.Flag) string { return fmt.Sprintf("\t\t%s", fl.GetName()) } } type hexWriter struct{} func (w *hexWriter) Write(p []byte) (int, error) { for _, b := range p { fmt.Printf("%x", b) } fmt.Printf("\n") return len(p), nil } type genericType struct{ s string } func (g *genericType) Set(value string) error { g.s = value return nil } func (g *genericType) String() string { return g.s } func main() { app := cli.NewApp() app.Name = "kənˈtrīv" app.Version = "19.99.0" app.Compiled = time.Now() app.Authors = []cli.Author{ cli.Author{ Name: "Example Human", Email: "human@example.com", }, } app.Copyright = "(c) 1999 Serious Enterprise" app.HelpName = "contrive" app.Usage = "demonstrate available API" app.UsageText = "contrive - demonstrating the available API" app.ArgsUsage = "[args and such]" app.Commands = []cli.Command{ cli.Command{ Name: "doo", Aliases: []string{"do"}, Category: "motion", Usage: "do the doo", UsageText: "doo - does the dooing", Description: "no really, there is a lot of dooing to be done", ArgsUsage: "[arrgh]", Flags: []cli.Flag{ cli.BoolFlag{Name: "forever, forevvarr"}, }, Subcommands: cli.Commands{ cli.Command{ Name: "wop", Action: wopAction, }, }, SkipFlagParsing: false, HideHelp: false, Hidden: false, HelpName: "doo!", BashComplete: func(c *cli.Context) { fmt.Fprintf(c.App.Writer, "--better\n") }, Before: func(c *cli.Context) error { fmt.Fprintf(c.App.Writer, "brace for impact\n") return nil }, After: func(c *cli.Context) error { fmt.Fprintf(c.App.Writer, "did we lose anyone?\n") return nil }, Action: func(c *cli.Context) error { c.Command.FullName() c.Command.HasName("wop") c.Command.Names() c.Command.VisibleFlags() fmt.Fprintf(c.App.Writer, "dodododododoodododddooooododododooo\n") if c.Bool("forever") { c.Command.Run(c) } return nil }, OnUsageError: func(c *cli.Context, err error, isSubcommand bool) error { fmt.Fprintf(c.App.Writer, "for shame\n") return err }, }, } app.Flags = []cli.Flag{ cli.BoolFlag{Name: "fancy"}, cli.BoolTFlag{Name: "fancier"}, cli.DurationFlag{Name: "howlong, H", Value: time.Second * 3}, cli.Float64Flag{Name: "howmuch"}, cli.GenericFlag{Name: "wat", Value: &genericType{}}, cli.Int64Flag{Name: "longdistance"}, cli.Int64SliceFlag{Name: "intervals"}, cli.IntFlag{Name: "distance"}, cli.IntSliceFlag{Name: "times"}, cli.StringFlag{Name: "dance-move, d"}, cli.StringSliceFlag{Name: "names, N"}, cli.UintFlag{Name: "age"}, cli.Uint64Flag{Name: "bigage"}, } app.EnableBashCompletion = true app.HideHelp = false app.HideVersion = false app.BashComplete = func(c *cli.Context) { fmt.Fprintf(c.App.Writer, "lipstick\nkiss\nme\nlipstick\nringo\n") } app.Before = func(c *cli.Context) error { fmt.Fprintf(c.App.Writer, "HEEEERE GOES\n") return nil } app.After = func(c *cli.Context) error { fmt.Fprintf(c.App.Writer, "Phew!\n") return nil } app.CommandNotFound = func(c *cli.Context, command string) { fmt.Fprintf(c.App.Writer, "Thar be no %q here.\n", command) } app.OnUsageError = func(c *cli.Context, err error, isSubcommand bool) error { if isSubcommand { return err } fmt.Fprintf(c.App.Writer, "WRONG: %#v\n", err) return nil } app.Action = func(c *cli.Context) error { cli.DefaultAppComplete(c) cli.HandleExitCoder(errors.New("not an exit coder, though")) cli.ShowAppHelp(c) cli.ShowCommandCompletions(c, "nope") ``` -------------------------------- ### Full Example with YAML Input Source Source: https://github.com/stripe/smokescreen/blob/master/vendor/gopkg.in/urfave/cli.v1/README.md A complete application demonstrating how to use YAML files to provide flag values. It defines flags for 'test' (int) and 'load' (string). ```go package notmain import ( "fmt" "os" "github.com/urfave/cli" "github.com/urfave/cli/altsrc" ) func main() { app := cli.NewApp() flags := []cli.Flag{ altsrc.NewIntFlag(cli.IntFlag{Name: "test"}), cli.StringFlag{Name: "load"}, } app.Action = func(c *cli.Context) error { fmt.Println("yaml ist rad") return nil } app.Before = altsrc.InitInputSourceWithContext(flags, altsrc.NewYamlSourceFromFlagFunc("load")) app.Flags = flags app.Run(os.Args) } ``` -------------------------------- ### Full API Example with urfave/cli Source: https://github.com/stripe/smokescreen/blob/master/vendor/gopkg.in/urfave/cli.v1/README.md Demonstrates extensive usage of the cli.Context and cli.App functionalities, including showing help and version, managing categories and commands, accessing arguments, and setting context values. This is useful for understanding the full capabilities of the library within an application's action. ```go cli.ShowCompletions(c) cli.ShowSubcommandHelp(c) cli.ShowVersion(c) categories := c.App.Categories() categories.AddCommand("sounds", cli.Command{ Name: "bloop", }) for _, category := range c.App.Categories() { fmt.Fprintf(c.App.Writer, "%s\n", category.Name) fmt.Fprintf(c.App.Writer, "%#v\n", category.Commands) fmt.Fprintf(c.App.Writer, "%#v\n", category.VisibleCommands()) } fmt.Printf("%#v\n", c.App.Command("doo")) if c.Bool("infinite") { c.App.Run([]string{"app", "doo", "wop"}) } if c.Bool("forevar") { c.App.RunAsSubcommand(c) } c.App.Setup() fmt.Printf("%#v\n", c.App.VisibleCategories()) fmt.Printf("%#v\n", c.App.VisibleCommands()) fmt.Printf("%#v\n", c.App.VisibleFlags()) fmt.Printf("%#v\n", c.Args().First()) if len(c.Args()) > 0 { fmt.Printf("%#v\n", c.Args()[1]) } fmt.Printf("%#v\n", c.Args().Present()) fmt.Printf("%#v\n", c.Args().Tail()) set := flag.NewFlagSet("contrive", 0) nc := cli.NewContext(c.App, set, c) fmt.Printf("%#v\n", nc.Args()) fmt.Printf("%#v\n", nc.Bool("nope")) fmt.Printf("%#v\n", nc.BoolT("nerp")) fmt.Printf("%#v\n", nc.Duration("howlong")) fmt.Printf("%#v\n", nc.Float64("hay")) fmt.Printf("%#v\n", nc.Generic("bloop")) fmt.Printf("%#v\n", nc.Int64("bonk")) fmt.Printf("%#v\n", nc.Int64Slice("burnks")) fmt.Printf("%#v\n", nc.Int("bips")) fmt.Printf("%#v\n", nc.IntSlice("blups")) fmt.Printf("%#v\n", nc.String("snurt")) fmt.Printf("%#v\n", nc.StringSlice("snurkles")) fmt.Printf("%#v\n", nc.Uint("flub")) fmt.Printf("%#v\n", nc.Uint64("florb")) fmt.Printf("%#v\n", nc.GlobalBool("global-nope")) fmt.Printf("%#v\n", nc.GlobalBoolT("global-nerp")) fmt.Printf("%#v\n", nc.GlobalDuration("global-howlong")) fmt.Printf("%#v\n", nc.GlobalFloat64("global-hay")) fmt.Printf("%#v\n", nc.GlobalGeneric("global-bloop")) fmt.Printf("%#v\n", nc.GlobalInt("global-bips")) fmt.Printf("%#v\n", nc.GlobalIntSlice("global-blups")) fmt.Printf("%#v\n", nc.GlobalString("global-snurt")) fmt.Printf("%#v\n", nc.GlobalStringSlice("global-snurkles")) fmt.Printf("%#v\n", nc.FlagNames()) fmt.Printf("%#v\n", nc.GlobalFlagNames()) fmt.Printf("%#v\n", nc.GlobalIsSet("wat")) fmt.Printf("%#v\n", nc.GlobalSet("wat", "nope")) fmt.Printf("%#v\n", nc.NArg()) fmt.Printf("%#v\n", nc.NumFlags()) fmt.Printf("%#v\n", nc.Parent()) nc.Set("wat", "also-nope") ec := cli.NewExitError("ohwell", 86) fmt.Fprintf(c.App.Writer, "%d", ec.ExitCode()) fmt.Printf("made it!\n") return ec ``` -------------------------------- ### Run golangci-lint from the command line Source: https://github.com/stripe/smokescreen/blob/master/vendor/github.com/Microsoft/go-winio/README.md Install golangci-lint locally and run it from the repository root to check code quality. Use flags to control the output of lint errors. ```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 ./... ``` -------------------------------- ### Use v2 branch of urfave/cli Source: https://github.com/stripe/smokescreen/blob/master/vendor/gopkg.in/urfave/cli.v1/README.md Install the v2 branch of the urfave/cli package using go get. This branch is considered unstable. ```bash go get gopkg.in/urfave/cli.v2 ``` ```go import ( "gopkg.in/urfave/cli.v2" ) ``` -------------------------------- ### JSON Log Entry Example Source: https://github.com/stripe/smokescreen/blob/master/vendor/github.com/sirupsen/logrus/README.md Example of a log entry with caller information formatted as JSON. ```json {"animal":"penguin","level":"fatal","method":"github.com/sirupsen/arcticcreatures.migrate","msg":"a penguin swims by", "time":"2014-03-10 19:57:38.562543129 -0400 EDT"} ``` -------------------------------- ### Add or Update Dependencies Source: https://github.com/stripe/smokescreen/blob/master/vendor/github.com/prometheus/procfs/CONTRIBUTING.md Use 'go get' to add or update external packages. Remember to commit the changes to go.mod, go.sum, and the vendor directory. ```bash # Pick the latest tagged release. go get example.com/some/module/pkg # Pick a specific version. go get example.com/some/module/pkg@vX.Y.Z ``` -------------------------------- ### Pin to v1 releases of urfave/cli Source: https://github.com/stripe/smokescreen/blob/master/vendor/gopkg.in/urfave/cli.v1/README.md Install a specific v1 release of the urfave/cli package using go get to avoid potential compatibility issues with v2. ```bash go get gopkg.in/urfave/cli.v1 ``` ```go import ( "gopkg.in/urfave/cli.v1" ) ``` -------------------------------- ### Customize Help Flag Source: https://github.com/stripe/smokescreen/blob/master/vendor/gopkg.in/urfave/cli.v1/README.md Customize the help flag by setting `cli.HelpFlag`. This example defines a new flag with the name `halp` and usage `HALP`. ```go package main import ( "os" "github.com/urfave/cli" ) func main() { cli.HelpFlag = cli.BoolFlag{ Name: "halp, haaaaalp", Usage: "HALP", EnvVar: "SHOW_HALP,HALPPLZ", } cli.NewApp().Run(os.Args) } ``` -------------------------------- ### Initialize Block Device FS and Get Disk Stats Source: https://github.com/stripe/smokescreen/blob/master/vendor/github.com/prometheus/procfs/README.md Initializes a filesystem object that accesses both /proc and /sys, then retrieves block device statistics. Required when data spans both filesystems. ```go fs, err := blockdevice.NewFS("/proc", "/sys") stats, err := fs.ProcDiskstats() ``` -------------------------------- ### Text Log Entry Example Source: https://github.com/stripe/smokescreen/blob/master/vendor/github.com/sirupsen/logrus/README.md Example of a log entry with caller information formatted as text. ```text time="2015-03-26T01:27:38-04:00" level=fatal method=github.com/sirupsen/arcticcreatures.migrate msg="a penguin swims by" animal=penguin ``` -------------------------------- ### Organize Subcommands with Categories Source: https://github.com/stripe/smokescreen/blob/master/vendor/gopkg.in/urfave/cli.v1/README.md Groups subcommands under categories in the help output for better organization. This example shows 'add' and 'remove' commands categorized under 'template'. ```go package main import ( "os" "github.com/urfave/cli" ) func main() { app := cli.NewApp() app.Commands = []cli.Command{ { Name: "noop", }, { Name: "add", Category: "template", }, { Name: "remove", Category: "template", }, } app.Run(os.Args) } ``` -------------------------------- ### Text Formatter Output (No TTY) Source: https://github.com/stripe/smokescreen/blob/master/vendor/github.com/sirupsen/logrus/README.md Example output using the default TextFormatter when a TTY is not attached. This format is compatible with logfmt. ```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 ``` -------------------------------- ### Generate TLS certificates for mTLS setup Source: https://github.com/stripe/smokescreen/blob/master/Development.md Bash commands to generate CA certificates, server/client keys, and certificate requests for setting up mTLS with Smokescreen. ```bash mkdir -p mtls_setup # Private keys for CAs openssl genrsa -out mtls_setup/server-ca.key 2048 openssl genrsa -out mtls_setup/client-ca.key 2048 # Generate client and server CA certificates openssl req -new -x509 -nodes -days 1000 -key mtls_setup/server-ca.key -out mtls_setup/server-ca.crt \ -subj "/C=AQ/ST=Petrel Island/L=Dumont-d'Urville /O=Penguin/OU=Publishing house/CN=server CA" openssl req -new -x509 -nodes -days 1000 -key mtls_setup/client-ca.key -out mtls_setup/client-ca.crt \ -subj "/C=MA/ST=Tarfaya/L=Tarfaya/O=Fennec/OU=Aviator/CN=Client CA" # Generate a certificate signing request (client CN is localhost which is used by smokescreen as the service name by default) openssl req -newkey rsa:2048 -nodes -keyout mtls_setup/server.key -out mtls_setup/server.req \ -subj "/C=AQ/ST=Petrel Island/L=Dumont-d'Urville/O=Chionis/OU=Publishing house/CN=server req" openssl req -newkey rsa:2048 -nodes -keyout mtls_setup/client.key -out mtls_setup/client.req \ -subj "/C=MA/ST=Tarfaya/L=Tarfaya/O=Addax/OU=Writer/CN=localhost" # Have the CA sign the certificate requests and output the certificates. echo "authorityKeyIdentifier=keyid,issuer basicConstraints=CA:FALSE keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment subjectAltName = @alt_names [alt_names] DNS.1 = localhost " > mtls_setup/localhost.ext openssl x509 -req -in mtls_setup/server.req -days 1000 -CA mtls_setup/server-ca.crt -CAkey mtls_setup/server-ca.key -set_serial 01 -out mtls_setup/server.crt -extfile mtls_setup/localhost.ext openssl x509 -req -in mtls_setup/client.req -days 1000 -CA mtls_setup/client-ca.crt -CAkey mtls_setup/client-ca.key -set_serial 01 -out mtls_setup/client.crt ``` -------------------------------- ### Customize CLI Version Printer Source: https://github.com/stripe/smokescreen/blob/master/vendor/gopkg.in/urfave/cli.v1/README.md Override the default version printer to format the version output differently. This example includes a 'revision' in the output. ```go package main import ( "fmt" "os" "github.com/urfave/cli" ) var ( Revision = "fafafaf" ) func main() { cli.VersionPrinter = func(c *cli.Context) { fmt.Printf("version=%s revision=%s\n", c.App.Version, Revision) } app := cli.NewApp() app.Name = "partay" app.Version = "19.99.0" app.Run(os.Args) } ``` -------------------------------- ### Rate Limiting Configuration (CLI) Source: https://github.com/stripe/smokescreen/blob/master/README.md Configure rate and concurrency limiting for Smokescreen using command-line arguments. This example sets limits for concurrent requests, request rate, and concurrent connect tunnels. ```bash smokescreen --max-concurrent-requests=100 --max-request-rate=50 --max-concurrent-connect-tunnels=50 ``` -------------------------------- ### Customizing Logrus Output and Level Source: https://github.com/stripe/smokescreen/blob/master/vendor/github.com/sirupsen/logrus/README.md Configures Logrus to log as JSON, output to stdout, and only log warnings or higher. Includes examples of Info, Warn, and Fatal log levels. ```go package main import ( "os" log "github.com/sirupsen/logrus" ) func init() { // Log as JSON instead of the default ASCII formatter. log.SetFormatter(&log.JSONFormatter{}) // Output to stdout instead of the default stderr // Can be any io.Writer, see below for File example log.SetOutput(os.Stdout) // Only log the warning severity or above. log.SetLevel(log.WarnLevel) } func main() { log.WithFields(log.Fields{ "animal": "walrus", "size": 10, }).Info("A group of walrus emerges from the ocean") log.WithFields(log.Fields{ "omg": true, "number": 122, }).Warn("The group's number increased tremendously!") log.WithFields(log.Fields{ "omg": true, "number": 100, }).Fatal("The ice breaks!") // A common pattern is to re-use fields between logging statements by re-using // the logrus.Entry returned from WithFields() contextLogger := log.WithFields(log.Fields{ "common": "this is a common field", "other": "I also should be logged always", }) contextLogger.Info("I'll be logged with common and other field") contextLogger.Info("Me too") } ``` -------------------------------- ### Replacing Standard Library Logger with Logrus Source: https://github.com/stripe/smokescreen/blob/master/vendor/github.com/sirupsen/logrus/README.md Override the standard library's log output to use a configured logrus logger. This example sets the output of the standard library's log package to the writer provided by a logrus logger configured with JSON formatting. ```go logger := logrus.New() logger.Formatter = &logrus.JSONFormatter{} // Use logrus for standard log output // Note that `log` here references stdlib's log // Not logrus imported under the name `log`. log.SetOutput(logger.Writer()) ``` -------------------------------- ### Application Configuration and Execution Source: https://github.com/stripe/smokescreen/blob/master/vendor/gopkg.in/urfave/cli.v1/README.md Shows how to configure application metadata, writers, and run the application with provided arguments. This is essential for setting up the entry point of a CLI application. ```go if os.Getenv("HEXY") != "" { app.Writer = &hexWriter{} app.ErrWriter = &hexWriter{} } app.Metadata = map[string]interface{}{ "layers": "many", "explicable": false, "whatever-values": 19.99, } app.Run(os.Args) } ``` -------------------------------- ### Create and Wrap a Listener with go-proxyproto Source: https://github.com/stripe/smokescreen/blob/master/vendor/github.com/armon/go-proxyproto/README.md Demonstrates how to create a standard net.Listener and then wrap it with the proxyproto.Listener to handle incoming connections using the PROXY protocol. ```go // Create a listener list, err := net.Listen("tcp", "...") // Wrap listener in a proxyproto listener proxyList := &proxyproto.Listener{Listener: list} conn, err :=proxyList.Accept() ... ``` -------------------------------- ### CLI App with Action and Usage Source: https://github.com/stripe/smokescreen/blob/master/vendor/gopkg.in/urfave/cli.v1/README.md Defines a CLI application with a name, usage string, and a simple action that prints a message. This demonstrates how to provide basic functionality and help documentation. ```go package main import ( "fmt" "os" "github.com/urfave/cli" ) func main() { app := cli.NewApp() app.Name = "boom" app.Usage = "make an explosive entrance" app.Action = func(c *cli.Context) error { fmt.Println("boom! I say!") return nil } app.Run(os.Args) } ``` -------------------------------- ### Curl with HTTPS_PROXY and mTLS Source: https://github.com/stripe/smokescreen/blob/master/Development.md Example of using cURL with HTTPS_PROXY and client certificates for mutual TLS authentication. ```bash HTTPS_PROXY=https://localhost:4750 curl --proxy-cacert mtls_setup/server-ca.crt --proxy-cert mtls_setup/client.crt --proxy-key mtls_setup/client.key https://api.github.com/zen ``` -------------------------------- ### Customize Bash Completion Flag Source: https://github.com/stripe/smokescreen/blob/master/vendor/gopkg.in/urfave/cli.v1/README.md Redefine the `cli.BashCompletionFlag` to customize the bash completion flag. This example sets it to `--compgen` and hides it. ```go package main import ( "os" "github.com/urfave/cli" ) func main() { cli.BashCompletionFlag = cli.BoolFlag{ Name: "compgen", Hidden: true, } app := cli.NewApp() app.EnableBashCompletion = true app.Commands = []cli.Command{ { Name: "wat", }, } app.Run(os.Args) } ``` -------------------------------- ### CLI App with Argument Handling Source: https://github.com/stripe/smokescreen/blob/master/vendor/gopkg.in/urfave/cli.v1/README.md Demonstrates how to access and use command-line arguments within a CLI application. The first argument is retrieved and used in a formatted output string. ```go package main import ( "fmt" "os" "github.com/urfave/cli" ) func main() { app := cli.NewApp() app.Action = func(c *cli.Context) error { fmt.Printf("Hello %q", c.Args().Get(0)) return nil } app.Run(os.Args) } ``` -------------------------------- ### Basic Usage of go-cache Source: https://github.com/stripe/smokescreen/blob/master/vendor/github.com/patrickmn/go-cache/README.md Demonstrates creating a cache with default and no expiration, setting and retrieving values, and handling type assertions for retrieved values. ```go import ( "fmt" "github.com/patrickmn/go-cache" "time" ) func main() { // Create a cache with a default expiration time of 5 minutes, and which // purges expired items every 10 minutes c := cache.New(5*time.Minute, 10*time.Minute) // Set the value of the key "foo" to "bar", with the default expiration time c.Set("foo", "bar", cache.DefaultExpiration) // Set the value of the key "baz" to 42, with no expiration time // (the item won't be removed until it is re-set, or removed using // c.Delete("baz") c.Set("baz", 42, cache.NoExpiration) // Get the string associated with the key "foo" from the cache foo, found := c.Get("foo") if found { fmt.Println(foo) } // Since Go is statically typed, and cache values can be anything, type // assertion is needed when values are being passed to functions that don't // take arbitrary types, (i.e. interface{}). The simplest way to do this for // values which will only be used once--e.g. for passing to another // function--is: foo, found := c.Get("foo") if found { MyFunction(foo.(string)) } // This gets tedious if the value is used several times in the same function. // You might do either of the following instead: if x, found := c.Get("foo"); found { foo := x.(string) // ... } // or var foo string if x, found := c.Get("foo"); found { foo = x.(string) } // ... // foo can then be passed around freely as a string // Want performance? Store pointers! c.Set("foo", &MyStruct, cache.DefaultExpiration) if x, found := c.Get("foo"); found { foo := x.(*MyStruct) // ... } } ``` -------------------------------- ### Create a Basic CLI App Source: https://github.com/stripe/smokescreen/blob/master/vendor/gopkg.in/urfave/cli.v1/README.md A minimal Go application using urfave/cli. This app will run and display help text when executed with '--help'. ```go package main import ( "os" "github.com/urfave/cli" ) func main() { cli.NewApp().Run(os.Args) } ``` -------------------------------- ### JSON Formatter Output Source: https://github.com/stripe/smokescreen/blob/master/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. ```json {"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 sys/unix with Old Build System Source: https://github.com/stripe/smokescreen/blob/master/vendor/golang.org/x/sys/unix/README.md Use this script for GOOS != "linux". It generates Go files based on local C header files. Ensure GOOS and GOARCH are set correctly. Running `mkall.sh` builds the files for your current system. ```bash mkall.sh ``` ```bash mkall.sh -n ``` -------------------------------- ### Read and Parse Files with procfs Source: https://github.com/stripe/smokescreen/blob/master/vendor/github.com/prometheus/procfs/CONTRIBUTING.md Demonstrates reading a file from /proc and then parsing its content using a scanner. This approach is recommended for /proc and /sys filesystems due to their dynamic nature. ```go data, err := util.ReadFileNoStat("/proc/cpuinfo") if err != nil { return err } reader := bytes.NewReader(data) scanner := bufio.NewScanner(reader) ``` -------------------------------- ### Basic Logrus Usage Source: https://github.com/stripe/smokescreen/blob/master/vendor/github.com/sirupsen/logrus/README.md Demonstrates the simplest way to use Logrus with the package-level exported logger. ```go package main import ( log "github.com/sirupsen/logrus" ) func main() { log.WithFields(log.Fields{ "animal": "walrus", }).Info("A walrus appears") } ``` -------------------------------- ### Customize CLI Version Flag Source: https://github.com/stripe/smokescreen/blob/master/vendor/gopkg.in/urfave/cli.v1/README.md Override the default version flag to use a custom name and usage. This example sets the version flag to 'print-version, V'. ```go package main import ( "os" "github.com/urfave/cli" ) func main() { cli.VersionFlag = cli.BoolFlag{ Name: "print-version, V", Usage: "print only the version", } app := cli.NewApp() app.Name = "partay" app.Version = "19.99.0" app.Run(os.Args) } ``` -------------------------------- ### Basic HTTP/HTTPS Proxy Server Source: https://github.com/stripe/smokescreen/blob/master/vendor/github.com/stripe/goproxy/README.md Sets up a basic HTTP/HTTPS proxy server that listens on port 8080. Enable Verbose to see proxy activity. ```go package main import ( "github.com/elazarl/goproxy" "log" "net/http" ) func main() { proxy := goproxy.NewProxyHttpServer() proxy.Verbose = true log.Fatal(http.ListenAndServe(":8080", proxy)) } ``` -------------------------------- ### xxhash Benchmark Commands Source: https://github.com/stripe/smokescreen/blob/master/vendor/github.com/cespare/xxhash/v2/README.md Commands to run benchmarks comparing pure Go and assembly implementations of xxhash. Ensure to use appropriate Go versions for compatibility. ```bash $ go test -tags purego -benchtime 10s -bench '/xxhash,direct,bytes' $ go test -benchtime 10s -bench '/xxhash,direct,bytes' ``` -------------------------------- ### Creating a Custom Logrus Instance Source: https://github.com/stripe/smokescreen/blob/master/vendor/github.com/sirupsen/logrus/README.md Demonstrates how to create and configure a separate instance of the Logrus logger, setting its output to stdout. ```go package main import ( "os" "github.com/sirupsen/logrus" ) // Create a new instance of the logger. You can have any number of instances. var log = logrus.New() func main() { // The API for setting attributes is a little different than the package level // exported logger. See Godoc. log.Out = os.Stdout // You could set this to any `io.Writer` such as a file // file, err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) // if err == nil { // log.Out = file // } else { // log.Info("Failed to log to file, using default stderr") // } log.WithFields(logrus.Fields{ "animal": "walrus", "size": 10, }).Info("A group of walrus emerges from the ocean") } ``` -------------------------------- ### Run all tests Source: https://github.com/stripe/smokescreen/blob/master/Development.md Execute all tests in the project. Ensure you are in the project root directory. ```bash go test ./... ``` -------------------------------- ### Structured Logging with Fields Source: https://github.com/stripe/smokescreen/blob/master/vendor/github.com/sirupsen/logrus/README.md Illustrates replacing printf-style fatal messages with structured logging using fields for better discoverability. ```go log.WithFields(log.Fields{ "event": event, "topic": topic, "key": key, }).Fatal("Failed to send event") ``` -------------------------------- ### Custom Client Identification in Go Source: https://github.com/stripe/smokescreen/blob/master/README.md Implement custom client identification logic by replacing the default `RoleFromRequest` function. This example splits the client certificate's OrganizationalUnit to determine the service name. ```go package main import (...) func main() { // Here is an opportunity to pass your logger conf, err := cmd.NewConfiguration(nil, nil) if err != nil { log.Fatal(err) } if conf == nil { os.Exit(1) } conf.RoleFromRequest = func(request *http.Request) (string, error) { fail := func(err error) (string, error) { return "", err } subject := request.TLS.PeerCertificates[0].Subject if len(subject.OrganizationalUnit) == 0 { fail(fmt.Errorf("warn: Provided cert has no 'OrganizationalUnit'. Can't extract service role.")) } return strings.SplitN(subject.OrganizationalUnit[0], ".", 2)[0], nil } smokescreen.StartWithConfig(conf, nil) } ``` -------------------------------- ### CLI App with String Flag Source: https://github.com/stripe/smokescreen/blob/master/vendor/gopkg.in/urfave/cli.v1/README.md Shows how to define and use a string flag ('lang') in a CLI application. The application's behavior changes based on the flag's value, allowing for different greetings. ```go package main import ( "fmt" "os" "github.com/urfave/cli" ) func main() { app := cli.NewApp() app.Flags = []cli.Flag { cli.StringFlag{ Name: "lang", Value: "english", Usage: "language for the greeting", }, } app.Action = func(c *cli.Context) error { name := "Nefertiti" if c.NArg() > 0 { name = c.Args().Get(0) } if c.String("lang") == "spanish" { fmt.Println("Hola", name) } else { fmt.Println("Hello", name) } return nil } app.Run(os.Args) } ``` -------------------------------- ### Rate Limiting Configuration (YAML) Source: https://github.com/stripe/smokescreen/blob/master/README.md Configure rate and concurrency limiting for Smokescreen using a YAML configuration file. This example sets limits for concurrent requests, request rate, request burst, and concurrent connect tunnels. ```yaml max_concurrent_requests: 100 max_request_rate: 50 max_request_burst: 150 # optional, defaults to 2x rate max_concurrent_connect_tunnels: 50 # limits active CONNECT tunnel connections ``` -------------------------------- ### Customize Help Text Templates Source: https://github.com/stripe/smokescreen/blob/master/vendor/gopkg.in/urfave/cli.v1/README.md Customize help text by reassigning `cli.AppHelpTemplate`, `cli.CommandHelpTemplate`, or `cli.SubcommandHelpTemplate`. Full override is possible by assigning a compatible func to `cli.HelpPrinter`. ```go package main import ( "fmt" "io" "os" "github.com/urfave/cli" ) func main() { // EXAMPLE: Append to an existing template cli.AppHelpTemplate = fmt.Sprintf(`%s WEBSITE: http://awesometown.example.com SUPPORT: support@awesometown.example.com `, cli.AppHelpTemplate) // EXAMPLE: Override a template cli.AppHelpTemplate = `NAME: {{.Name}} - {{.Usage}} USAGE: {{.HelpName}} {{if .VisibleFlags}}[global options]{{end}}{{if .Commands}} command [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}} {{if len .Authors}} AUTHOR: {{range .Authors}}{{ . }}{{end}} {{end}}{{if .Commands}} COMMANDS: {{range .Commands}}{{if not .HideHelp}} {{join .Names ", "}}{{ "\t"}}{{.Usage "\n"}}{{end}}{{end}}{{end}}{{if .VisibleFlags}} GLOBAL OPTIONS: {{range .VisibleFlags}}{{.}} {{end}}{{end}}{{if .Copyright }} COPYRIGHT: {{.Copyright}} {{end}}{{if .Version}} VERSION: {{.Version}} {{end}} ` // EXAMPLE: Replace the `HelpPrinter` func cli.HelpPrinter = func(w io.Writer, templ string, data interface{}) { fmt.Println("Ha HA. I pwnd the help!!1") } cli.NewApp().Run(os.Args) } ``` -------------------------------- ### Initialize Alternate Input Source (YAML) Source: https://github.com/stripe/smokescreen/blob/master/vendor/gopkg.in/urfave/cli.v1/README.md Initializes flag values from a YAML file. The 'load' flag specifies the YAML file name. Ensure the 'load' flag is also defined. ```go command.Before = altsrc.InitInputSourceWithContext(command.Flags, NewYamlSourceFromFlagFunc("load")) ``` -------------------------------- ### Custom JSON Formatter Implementation in Logrus Source: https://github.com/stripe/smokescreen/blob/master/vendor/github.com/sirupsen/logrus/README.md Implement a custom JSON formatter by defining a struct and implementing the Format method. This example shows how to marshal entry data to JSON. Consult `godoc` for default fields like Time, Level, and Message. ```go type MyJSONFormatter struct { } log.SetFormatter(new(MyJSONFormatter)) func (f *MyJSONFormatter) Format(entry *Entry) ([]byte, error) { // Note this doesn't include Time, Level and Message which are available on // the Entry. Consult `godoc` on information about those fields or read the // source of the official loggers. serialized, err := json.Marshal(entry.Data) if err != nil { return nil, fmt.Errorf("Failed to marshal fields to JSON, %w", err) } return append(serialized, '\n'), nil } ``` -------------------------------- ### Enable X-Server-Ip Header Source: https://github.com/stripe/smokescreen/blob/master/vendor/github.com/stripe/goproxy/README.md Initializes the proxy server with an option to add the 'X-Server-Ip' header to CONNECT responses. This header contains the remote server's IP address. ```go proxy := goproxy.NewProxyHttpServer(goproxy.WithAddServerIpHeader(true)) ``` -------------------------------- ### CLI App with Placeholder Flag Usage Source: https://github.com/stripe/smokescreen/blob/master/vendor/gopkg.in/urfave/cli.v1/README.md Defines a string flag with a placeholder in its usage string. This placeholder is used in the help output to indicate the expected value for the flag. ```go package main import ( "os" "github.com/urfave/cli" ) func main() { app := cli.NewApp() app.Flags = []cli.Flag{ cli.StringFlag{ Name: "config, c", Usage: "Load configuration from `FILE`", }, } app.Run(os.Args) } ``` -------------------------------- ### Run go generate for auto-generated code Source: https://github.com/stripe/smokescreen/blob/master/vendor/github.com/Microsoft/go-winio/README.md Execute 'go generate' from the command line to update any auto-generated code within the repository. ```shell > go generate ./... ``` -------------------------------- ### System Call Dispatch Entry Points Source: https://github.com/stripe/smokescreen/blob/master/vendor/golang.org/x/sys/unix/README.md These are the hand-written assembly entry points for system call dispatch in `asm_${GOOS}_${GOARCH}.s`. They differ in the number of arguments they accept. `RawSyscall` is for low-level use and bypasses the scheduler notification. ```go func Syscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr) ``` ```go func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr) ``` ```go func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr) ``` -------------------------------- ### Tidy and Vendor Dependencies Source: https://github.com/stripe/smokescreen/blob/master/vendor/github.com/prometheus/procfs/CONTRIBUTING.md After adding or updating dependencies, tidy the go.mod and go.sum files and then vendor the dependencies. ```bash # The GO111MODULE variable can be omitted when the code isn't located in GOPATH. GO111MODULE=on go mod tidy GO111MODULE=on go mod vendor ``` -------------------------------- ### Add Custom Logrus Hooks Source: https://github.com/stripe/smokescreen/blob/master/vendor/github.com/sirupsen/logrus/README.md Demonstrates how to add custom hooks for error tracking (Airbrake) and syslog integration in the init function. Ensure necessary packages are imported. ```go import ( log "github.com/sirupsen/logrus" "gopkg.in/gemnasium/logrus-airbrake-hook.v2" // the package is named "airbrake" logrus_syslog "github.com/sirupsen/logrus/hooks/syslog" "log/syslog" ) func init() { // Use the Airbrake hook to report errors that have Error severity or above to // an exception tracker. You can create custom hooks, see the Hooks section. log.AddHook(airbrake.NewHook(123, "xyz", "production")) hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "") if err != nil { log.Error("Unable to connect to local syslog daemon") } else { log.AddHook(hook) } } ``` -------------------------------- ### Read Small Files from /sys with procfs Source: https://github.com/stripe/smokescreen/blob/master/vendor/github.com/prometheus/procfs/CONTRIBUTING.md Shows how to read small files from the /sys filesystem using util.SysReadFile. This utility is optimized for files containing single values and avoids unnecessary size checks. ```go data, err := util.SysReadFile("/sys/class/power_supply/BAT0/capacity") ``` -------------------------------- ### Unmarshal and Marshal YAML Data in Go Source: https://github.com/stripe/smokescreen/blob/master/vendor/gopkg.in/yaml.v2/README.md Demonstrates how to unmarshal YAML data into a Go struct and a map, and then marshal them back into YAML format. Ensure struct fields are public for correct unmarshalling. ```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)) } ```