### Install gziphandler Source: https://github.com/carvel-dev/kapp-controller/blob/develop/vendor/github.com/NYTimes/gziphandler/README.md Install the gziphandler package using go get. ```bash go get -u github.com/NYTimes/gziphandler ``` -------------------------------- ### Install Flect Source: https://github.com/carvel-dev/kapp-controller/blob/develop/vendor/github.com/gobuffalo/flect/README.md Install the flect package using the go get command. ```console $ go get github.com/gobuffalo/flect ``` -------------------------------- ### Install Go Color Library Source: https://github.com/carvel-dev/kapp-controller/blob/develop/cli/vendor/github.com/cppforlife/color/README.md Install the color library using go get. ```bash go get github.com/fatih/color ``` -------------------------------- ### Define a WebService and Routes Source: https://github.com/carvel-dev/kapp-controller/blob/develop/cli/vendor/github.com/emicklei/go-restful/v3/README.md Example of setting up a new WebService, defining its path, supported content types, and a GET route for retrieving a user. This snippet demonstrates basic route configuration including path parameters and response types. ```go ws := new(restful.WebService) ws. Path("/users"). Consumes(restful.MIME_XML, restful.MIME_JSON). Produces(restful.MIME_JSON, restful.MIME_XML) ws.Route(ws.GET("/{user-id}").To(u.findUser). Doc("get a user"). Param(ws.PathParameter("user-id", "identifier of the user").DataType("string")), Writes(User{})) ... func (u UserResource) findUser(request *restful.Request, response *restful.Response) { id := request.PathParameter("user-id") ... } ``` -------------------------------- ### Install and Run Local Go Doc Site Source: https://github.com/carvel-dev/kapp-controller/blob/develop/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Installs the pkgsite tool and runs a local Go documentation site. Ensure you have Go installed and configured. ```sh go install golang.org/x/pkgsite/cmd/pkgsite@latest pkgsite ``` -------------------------------- ### Install go.yaml.in/yaml/v3 Source: https://github.com/carvel-dev/kapp-controller/blob/develop/cli/vendor/go.yaml.in/yaml/v3/README.md Install the YAML package for Go using the go get command. ```bash go get go.yaml.in/yaml/v3 ``` -------------------------------- ### Install json-iterator/go Source: https://github.com/carvel-dev/kapp-controller/blob/develop/cli/vendor/github.com/json-iterator/go/README.md Use the go get command to install the json-iterator/go library. ```go go get github.com/json-iterator/go ``` -------------------------------- ### Install Go Version Library Source: https://github.com/carvel-dev/kapp-controller/blob/develop/cli/vendor/github.com/hashicorp/go-version/README.md Install the go-version library using the standard Go toolchain. ```bash $ go get github.com/hashicorp/go-version ``` -------------------------------- ### Install and Import invopop/yaml Source: https://github.com/carvel-dev/kapp-controller/blob/develop/cli/vendor/github.com/oasdiff/yaml/README.md Install the package using go get and import it into your Go project. ```bash $ go get github.com/invopop/yaml ``` ```go import "github.com/invopop/yaml" ``` -------------------------------- ### Install uuid Package Source: https://github.com/carvel-dev/kapp-controller/blob/develop/cli/vendor/github.com/google/uuid/README.md Install the uuid package using the go get command. ```sh go get github.com/google/uuid ``` -------------------------------- ### Install etcd/client/v3 Source: https://github.com/carvel-dev/kapp-controller/blob/develop/vendor/go.etcd.io/etcd/client/v3/README.md Install the etcd client library using go modules. ```bash go get go.etcd.io/etcd/client/v3 ``` -------------------------------- ### Install and Import YAML Package Source: https://github.com/carvel-dev/kapp-controller/blob/develop/cli/vendor/sigs.k8s.io/yaml/README.md Install the package using go get and import it into your Go project. ```bash $ go get sigs.k8s.io/yaml ``` ```go import "sigs.k8s.io/yaml" ``` -------------------------------- ### Install Cobra Library Source: https://github.com/carvel-dev/kapp-controller/blob/develop/cli/vendor/github.com/spf13/cobra/README.md Install the latest version of the Cobra library using go get. ```bash go get -u github.com/spf13/cobra@latest ``` -------------------------------- ### Install difflib Go Package Source: https://github.com/carvel-dev/kapp-controller/blob/develop/cli/vendor/github.com/k14s/difflib/README.md Use 'go get' to install the difflib library. This command fetches and installs the package and its dependencies. ```bash go get github.com/aryann/difflib ``` -------------------------------- ### Install Package Source: https://github.com/carvel-dev/kapp-controller/blob/develop/examples/local-kind-environment/README.md Applies the package installation configuration using kubectl. ```sh kubectl apply -f package_install.yml ``` -------------------------------- ### Install go.uber.org/multierr Source: https://github.com/carvel-dev/kapp-controller/blob/develop/cli/vendor/go.uber.org/multierr/README.md Install the latest version of the multierr library using go get. ```bash go get -u go.uber.org/multierr@latest ``` -------------------------------- ### Install go-isatty Package Source: https://github.com/carvel-dev/kapp-controller/blob/develop/cli/vendor/github.com/mattn/go-isatty/README.md Use this command to install the go-isatty package into your Go project. ```bash go get github.com/mattn/go-isatty ``` -------------------------------- ### Install Marshmallow Go Package Source: https://github.com/carvel-dev/kapp-controller/blob/develop/cli/vendor/github.com/perimeterx/marshmallow/README.md Use go get to install the Marshmallow package. This command fetches and installs the latest version of the package. ```sh go get -u github.com/perimeterx/marshmallow ``` -------------------------------- ### Coexisting with klog/v1 Source: https://github.com/carvel-dev/kapp-controller/blob/develop/cli/vendor/k8s.io/klog/v2/README.md Provides an example demonstrating how to use both klog/v1 and klog/v2 within the same project. ```go // See examples/coexist_klog_v1_and_v2/ ``` -------------------------------- ### Basic Test Script Example Source: https://github.com/carvel-dev/kapp-controller/blob/develop/cli/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md Illustrates creating a file and writing data to it, showing the expected fsnotify events. ```shell # Create a new empty file with some data. watch / echo data >/file Output: create /file write /file ``` -------------------------------- ### Install Package Repository Source: https://github.com/carvel-dev/kapp-controller/blob/develop/examples/local-kind-environment/README.md Applies the package repository installation configuration using kubectl. ```sh kubectl apply -f package_repository_install.yml ``` -------------------------------- ### Install go-colorable Package Source: https://github.com/carvel-dev/kapp-controller/blob/develop/cli/vendor/github.com/mattn/go-colorable/README.md Use this command to install the go-colorable package into your Go project. ```bash $ go get github.com/mattn/go-colorable ``` -------------------------------- ### String Substring Examples Source: https://github.com/carvel-dev/kapp-controller/blob/develop/vendor/github.com/google/cel-go/ext/README.md Shows how to extract substrings using start and optional end indices. Errors are raised for invalid ranges. ```cel 'tacocat'.substring(4) // returns 'cat' ``` ```cel 'tacocat'.substring(0, 4) // returns 'taco' ``` ```cel 'tacocat'.substring(-1) // error ``` ```cel 'tacocat'.substring(2, 1) // error ``` -------------------------------- ### Install Kapp Controller Source: https://github.com/carvel-dev/kapp-controller/blob/develop/examples/local-kind-environment/README.md Installs the latest release of Kapp Controller using kubectl. ```sh kubectl apply -f https://github.com/carvel-dev/kapp-controller/releases/latest/download/release.yml ``` -------------------------------- ### Go Float16 Conversion Examples Source: https://github.com/carvel-dev/kapp-controller/blob/develop/cli/vendor/github.com/x448/float16/README.md Demonstrates converting between float32 and float16 using the float16 package. Includes examples for direct conversion and conditional conversion based on precision. ```Go import ( "math" "github.com/x448/float16" ) // Convert float32 to float16 pi := float32(math.Pi) pi16 := float16.Fromfloat32(pi) // Convert float16 to float32 pi32 := pi16.Float32() // PrecisionFromfloat32() is faster than the overhead of calling a function. // This example only converts if there's no data loss and input is not a subnormal. if float16.PrecisionFromfloat32(pi) == float16.PrecisionExact { pi16 := float16.Fromfloat32(pi) } ``` -------------------------------- ### Initialize Procfs and Get Stat Source: https://github.com/carvel-dev/kapp-controller/blob/develop/cli/vendor/github.com/prometheus/procfs/README.md Initializes the proc filesystem and retrieves CPU statistics from /proc/stat. ```go fs, err := procfs.NewFS("/proc") stats, err := fs.Stat() ``` -------------------------------- ### String Split Examples Source: https://github.com/carvel-dev/kapp-controller/blob/develop/vendor/github.com/google/cel-go/ext/README.md Illustrates the string split function with different separators and limits. ```cel 'hello hello hello'.split(' ') // returns ['hello', 'hello', 'hello'] ``` ```cel 'hello hello hello'.split(' ', 0) // returns [] ``` ```cel 'hello hello hello'.split(' ', 1) // returns ['hello hello hello'] ``` ```cel 'hello hello hello'.split(' ', 2) // returns ['hello', 'hello hello'] ``` ```cel 'hello hello hello'.split(' ', -1) // returns ['hello', 'hello', 'hello'] ``` -------------------------------- ### Platform-Specific Test Example Source: https://github.com/carvel-dev/kapp-controller/blob/develop/cli/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md Demonstrates how to define platform-specific test outputs within a script. ```shell watch / touch /file Output: # Tested if nothing else matches create /file # Windows-specific test. windows: write /file ``` -------------------------------- ### Constructor Functions for Dog and Bird Source: https://github.com/carvel-dev/kapp-controller/blob/develop/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Example constructor functions for 'Dog' and 'Bird' that accept specific options for their respective types. ```go func NewDog(name string, o ...DogOption) Dog {…} func NewBird(name string, o ...BirdOption) Bird {…} ``` -------------------------------- ### String Replace Examples Source: https://github.com/carvel-dev/kapp-controller/blob/develop/vendor/github.com/google/cel-go/ext/README.md Demonstrates the string replace function with and without a replacement limit. ```cel 'hello hello'.replace('he', 'we') // returns 'wello wello' ``` ```cel 'hello hello'.replace('he', 'we', -1) // returns 'wello wello' ``` ```cel 'hello hello'.replace('he', 'we', 1) // returns 'wello hello' ``` ```cel 'hello hello'.replace('he', 'we', 0) // returns 'hello hello' ``` -------------------------------- ### Add or Update Dependency Source: https://github.com/carvel-dev/kapp-controller/blob/develop/cli/vendor/github.com/prometheus/procfs/CONTRIBUTING.md Use 'go get' to add or update external package dependencies. ```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 ``` -------------------------------- ### Enable gRPC-Go Logging Source: https://github.com/carvel-dev/kapp-controller/blob/develop/vendor/google.golang.org/grpc/README.md Set environment variables to control the verbosity and severity of gRPC-Go logs. This example enables all logging. ```sh export GRPC_GO_LOG_VERBOSITY_LEVEL=99 export GRPC_GO_LOG_SEVERITY_LEVEL=info ``` -------------------------------- ### Basic fsnotify Watcher Example Source: https://github.com/carvel-dev/kapp-controller/blob/develop/cli/vendor/github.com/fsnotify/fsnotify/README.md Demonstrates how to create a new watcher, add a directory to watch, and listen for file system events (write, errors) in a separate goroutine. It's essential to close the watcher when done. ```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{})) } ``` -------------------------------- ### Define a WebService and Routes in Go Source: https://github.com/carvel-dev/kapp-controller/blob/develop/vendor/github.com/emicklei/go-restful/v3/README.md Example demonstrating how to define a WebService with path, consumes, produces, and routes. Includes a handler function for finding a user by ID. ```go ws := new(restful.WebService) ws. Path("/users"). Consumes(restful.MIME_XML, restful.MIME_JSON). Produces(restful.MIME_JSON, restful.MIME_XML) ws.Route(ws.GET("/{user-id}").To(u.findUser). Doc("get a user"). Param(ws.PathParameter("user-id", "identifier of the user").DataType("string")), Writes(User{})) ... func (u UserResource) findUser(request *restful.Request, response *restful.Response) { id := request.PathParameter("user-id") ... } ``` -------------------------------- ### Create Root Logger in Go Application Source: https://github.com/carvel-dev/kapp-controller/blob/develop/cli/vendor/github.com/go-logr/logr/README.md Demonstrates how to create the initial 'root' logger instance in an application's main function, choosing a specific logging implementation like 'logimpl'. This setup is done early in the application's lifecycle. ```go func main() { // ... other setup code ... // Create the "root" logger. We have chosen the "logimpl" implementation, // which takes some initial parameters and returns a logr.Logger. logger := logimpl.New(param1, param2) // ... other setup code ... ``` -------------------------------- ### Install Latest JSON-Patch Source: https://github.com/carvel-dev/kapp-controller/blob/develop/cli/vendor/gopkg.in/evanphx/json-patch.v4/README.md Use this command to get the latest version of the jsonpatch library. ```bash go get -u github.com/evanphx/json-patch/v5 ``` -------------------------------- ### Deploy a Sample MongoDB Replica Set Source: https://github.com/carvel-dev/kapp-controller/blob/develop/cli/examples/package-authoring/mongodb-enterprise-operator/upstream/README.md Applies a sample configuration to deploy a 3-member MongoDB Replica Set. Use the --namespace option if deploying to a specific namespace. ```shell kubectl apply -f https://raw.githubusercontent.com/mongodb/mongodb-enterprise-kubernetes/master/samples/mongodb/minimal/replica-set.yaml [--namespace mongodb] ``` -------------------------------- ### Install JSON-Patch v4 Source: https://github.com/carvel-dev/kapp-controller/blob/develop/cli/vendor/gopkg.in/evanphx/json-patch.v4/README.md Use this command to get version 4 of the jsonpatch library if needed. ```bash go get -u gopkg.in/evanphx/json-patch.v4 ``` -------------------------------- ### Example Go Module Requirement (Incorrect) Source: https://github.com/carvel-dev/kapp-controller/blob/develop/vendor/github.com/antlr4-go/antlr/v4/README.md Illustrates the unclear module reference obtained when using `go get` directly from the deeply nested ANTLR4 repository. ```go require ( github.com/antlr/antlr4/runtime/Go/antlr/v4 v4.0.0-20230219212500-1f9a474dc2dc ) ``` -------------------------------- ### Basic fsnotify Watcher Usage in Go Source: https://github.com/carvel-dev/kapp-controller/blob/develop/vendor/github.com/fsnotify/fsnotify/README.md Demonstrates how to create a new watcher, listen for events and errors in a goroutine, add a directory to watch, and handle potential errors. It's recommended to ignore Chmod events as they can be noisy. ```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{}) } ``` -------------------------------- ### Example using TagSet and TagOptions Source: https://github.com/carvel-dev/kapp-controller/blob/develop/cli/vendor/github.com/fxamacker/cbor/v2/README.md Shows how to create a TagSet, register a custom tag (COSE_Sign1 18) with a specific type, and then use this TagSet to create decoding and encoding modes. ```go // Use signedCWT struct defined in "Decoding CWT" example. // Create TagSet (safe for concurrency). tags := cbor.NewTagSet() // Register tag COSE_Sign1 18 with signedCWT type. tags.Add( cbor.TagOptions{EncTag: cbor.EncTagRequired, DecTag: cbor.DecTagRequired}, reflect.TypeOf(signedCWT{}), 18) // Create DecMode with immutable tags. dm, _ := cbor.DecOptions{}.DecModeWithTags(tags) // Unmarshal to signedCWT with tag support. var v signedCWT if err := dm.Unmarshal(data, &v); err != nil { return err } // Create EncMode with immutable tags. em, _ := cbor.EncOptions{}.EncModeWithTags(tags) // Marshal signedCWT with tag number. if data, err := em.Marshal(v); err != nil { return err } ``` -------------------------------- ### Install Cobra CLI Generator Source: https://github.com/carvel-dev/kapp-controller/blob/develop/vendor/github.com/spf13/cobra/README.md Installs the cobra-cli tool, used for scaffolding Cobra applications. ```bash go install github.com/spf13/cobra-cli@latest ``` -------------------------------- ### Initialize Package Build Source: https://github.com/carvel-dev/kapp-controller/blob/develop/cli/examples/package-authoring/mongodb-enterprise-operator/README.md Run `kctrl pkg init` to initialize the package build. This command reads configuration from `package-build.yml` and `vendir.yml` and prompts for default values, including the Helm Chart version. ```shell cd cli/examples/mongodb-enterprise-operator kctrl pkg init ``` -------------------------------- ### Initialize Package with kctrl Source: https://github.com/carvel-dev/kapp-controller/blob/develop/cli/examples/package-authoring/redis-enterprise-operator/README.md Initializes the package for the Redis Enterprise Operator. Navigate to the example directory and run `kctrl pkg init`. ```shell cd cli/examples/redis-enterprise-operator kctrl pkg init ``` -------------------------------- ### Find the first occurrence of a substring Source: https://github.com/carvel-dev/kapp-controller/blob/develop/vendor/github.com/google/cel-go/ext/README.md Use indexOf to find the starting index of a substring within a string. Returns -1 if not found. An optional starting position can be provided. Returns the starting index if the search string is empty. ```cel 'hello mellow'.indexOf('') // returns 0 'hello mellow'.indexOf('ello') // returns 1 'hello mellow'.indexOf('jello') // returns -1 'hello mellow'.indexOf('', 2) // returns 2 'hello mellow'.indexOf('ello', 2) // returns 7 'hello mellow'.indexOf('ello', 20) // returns -1 'hello mellow'.indexOf('ello', -1) // error ``` -------------------------------- ### Run difflib Demo Application Source: https://github.com/carvel-dev/kapp-controller/blob/develop/cli/vendor/github.com/k14s/difflib/README.md Execute the difflib demo application by providing two file paths as arguments. The demo starts a web server to display diff results. ```bash go run src/github.com/aryann/difflib/difflib_server/difflib_demo.go ``` -------------------------------- ### Install Enterprise Operator in a Specific Namespace Source: https://github.com/carvel-dev/kapp-controller/blob/develop/cli/examples/package-authoring/mongodb-enterprise-operator/upstream/README.md Installs the Enterprise Operator in the 'mongodb' namespace, creating the namespace if it does not exist. ```shell helm install enterprise-operator mongodb/enterprise-operator --namespace mongodb [--create-namespace] ``` -------------------------------- ### Build Kapp-Controller Project Source: https://github.com/carvel-dev/kapp-controller/blob/develop/docs/dev.md Run this script to build the kapp-controller project locally. ```bash ./hack/build.sh ``` -------------------------------- ### Install Cobra CLI Generator Source: https://github.com/carvel-dev/kapp-controller/blob/develop/cli/vendor/github.com/spf13/cobra/README.md Install the cobra-cli command line program, used for generating Cobra application and command files. ```bash go install github.com/spf13/cobra-cli@latest ``` -------------------------------- ### Check Version Against Constraints in Go Source: https://github.com/carvel-dev/kapp-controller/blob/develop/cli/vendor/github.com/hashicorp/go-version/README.md Shows how to create a version constraint and check if a given version satisfies it. Assumes err is handled. ```go v1, err := version.NewVersion("1.2") // Constraints example. constraints, err := version.NewConstraint(">= 1.0, < 1.4") if constraints.Check(v1) { fmt.Printf("%s satisfies constraints %s", v1, constraints) } ``` -------------------------------- ### Install MongoDB Enterprise Operator Source: https://github.com/carvel-dev/kapp-controller/blob/develop/cli/examples/package-authoring/mongodb-enterprise-operator/upstream/README.md Installs the Enterprise Operator in the current namespace. Use the --namespace flag to specify a different namespace. ```shell helm install enterprise-operator mongodb/enterprise-operator ``` -------------------------------- ### Using Zapr with Logr Source: https://github.com/carvel-dev/kapp-controller/blob/develop/cli/vendor/github.com/go-logr/zapr/README.md Demonstrates how to initialize a logr.Logger using zapr and an Uber Zap logger. This is useful for projects already using the logr interface. ```go package main import ( "fmt" "go.uber.org/zap" "github.com/go-logr/logr" "github.com/go-logr/zapr" ) func main() { var log logr.Logger zapLog, err := zap.NewDevelopment() if err != nil { panic(fmt.Sprintf("who watches the watchmen (%v)?", err)) } log = zapr.NewLogger(zapLog) log.Info("Logr in action!", "the answer", 42) } ``` -------------------------------- ### Start Local Docker Registry Source: https://github.com/carvel-dev/kapp-controller/blob/develop/test/e2e/assets/registry/instructions-for-one-time-setup.txt Starts a Docker registry container in detached mode, mapping port 5000 and persisting data to /tmp/registry. ```bash docker run -d -p 5000:5000 --restart=always -v/tmp/registry:/var/lib/registry --name registry registry:2 ``` -------------------------------- ### Get OpenTelemetry Go Module Source: https://github.com/carvel-dev/kapp-controller/blob/develop/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Use `go get` to download the OpenTelemetry Go module, which places the project in your GOPATH. This command may print warnings that can be ignored. ```go go get -d go.opentelemetry.io/otel ``` -------------------------------- ### Build Package Repository Bundle Source: https://github.com/carvel-dev/kapp-controller/blob/develop/examples/local-kind-environment/README.md Uses kbld to build the package repository bundle, outputting an imgpkg lock file. ```sh kbld -f ./package-repository/packages --imgpkg-lock-output "./package-repository/.imgpkg/images.yml" ``` -------------------------------- ### Parse and Compare Versions in Go Source: https://github.com/carvel-dev/kapp-controller/blob/develop/cli/vendor/github.com/hashicorp/go-version/README.md Demonstrates parsing version strings into Version objects and comparing them using LessThan. Assumes err is handled. ```go v1, err := version.NewVersion("1.2") v2, err := version.NewVersion("1.5+metadata") // Comparison example. There is also GreaterThan, Equal, and just // a simple Compare that returns an int allowing easy >=, <=, etc. if v1.LessThan(v2) { fmt.Printf("%s is less than %s", v1, v2) } ``` -------------------------------- ### Gob Encoding Security Vulnerability Example Source: https://github.com/carvel-dev/kapp-controller/blob/develop/cli/vendor/github.com/fxamacker/cbor/v2/README.md Illustrates a 'fatal error: runtime: out of memory' when decoding malicious data using Go's encoding/gob. This example highlights the security risks associated with gob when handling untrusted inputs. ```Go package main import ( "bytes" "encoding/gob" "encoding/hex" "fmt" ) // Example data is from https://github.com/golang/go/issues/24446 // (shortened to 181 bytes). const data = "4dffb503010102303001ff30000109010130010800010130010800010130" "01ffb80001014a01ffb60001014b01ff860001013001ff860001013001ff" "860001013001ff860001013001ffb80000001eff850401010e30303030" "303030303030303030303030303030303030303030303030303030303030" "303030303030303030303030303030303030303030303030303030303030" "30" type X struct { J *X K map[string]int } func main() { raw, _ := hex.DecodeString(data) decoder := gob.NewDecoder(bytes.NewReader(raw)) var x X decoder.Decode(&x) // fatal error: runtime: out of memory fmt.Println("Decoding finished.") } ``` -------------------------------- ### Base64.Encode Example Source: https://github.com/carvel-dev/kapp-controller/blob/develop/vendor/github.com/google/cel-go/ext/README.md Encodes bytes to a base64-encoded string. ```cel base64.encode(b'hello') // return 'aGVsbG8=' ``` -------------------------------- ### Example using Embedded JSON Tag for CBOR (tag 262) Source: https://github.com/carvel-dev/kapp-controller/blob/develop/cli/vendor/github.com/fxamacker/cbor/v2/README.md Demonstrates encoding and decoding a CBOR data item with tag number 262, where the tag content is a JSON object embedded as a CBOR byte string. This example implements custom MarshalCBOR and UnmarshalCBOR methods. ```go // https://github.com/fxamacker/cbor/issues/657 package cbor_test // NOTE: RFC 8949 does not mention tag number 262. IANA assigned // CBOR tag number 262 as "Embedded JSON Object" specified by the // document Embedded JSON Tag for CBOR: // // "Tag 262 can be applied to a byte string (major type 2) to indicate // that the byte string is a JSON Object. The length of the byte string // indicates the content." // // For more info, see Embedded JSON Tag for CBOR at: // https://github.com/toravir/CBOR-Tag-Specs/blob/master/embeddedJSON.md import ( "bytes" "encoding/json" "fmt" "github.com/fxamacker/cbor/v2" ) // cborTagNumForEmbeddedJSON is the CBOR tag number 262. const cborTagNumForEmbeddedJSON = 262 // EmbeddedJSON represents a Go value to be encoded as a tagged CBOR data item // with tag number 262 and the tag content is a JSON object "embedded" as a // CBOR byte string (major type 2). type EmbeddedJSON struct { any } func NewEmbeddedJSON(val any) EmbeddedJSON { return EmbeddedJSON{val} } // MarshalCBOR encodes EmbeddedJSON to a tagged CBOR data item with the // tag number 262 and the tag content is a JSON object that is // "embedded" as a CBOR byte string. func (v EmbeddedJSON) MarshalCBOR() ([]byte, error) { // Encode v to JSON object. data, err := json.Marshal(v) if err != nil { return nil, err } // Create cbor.Tag representing a tagged CBOR data item. tag := cbor.Tag{ Number: cborTagNumForEmbeddedJSON, Content: data, } // Marshal to a tagged CBOR data item. return cbor.Marshal(tag) } // UnmarshalCBOR decodes a tagged CBOR data item to EmbeddedJSON. // The byte slice provided to this function must contain a single // tagged CBOR data item with the tag number 262 and tag content // must be a JSON object "embedded" as a CBOR byte string. func (v *EmbeddedJSON) UnmarshalCBOR(b []byte) error { // Unmarshal tagged CBOR data item. var tag cbor.Tag if err := cbor.Unmarshal(b, &tag); err != nil { return err } // Check tag number. if tag.Number != cborTagNumForEmbeddedJSON { return fmt.Errorf("got tag number %d, expect tag number %d", tag.Number, cborTagNumForEmbeddedJSON) } // Check tag content. jsonData, isByteString := tag.Content.([]byte) if !isByteString { return fmt.Errorf("got tag content type %T, expect tag content []byte", tag.Content) } // Unmarshal JSON object. return json.Unmarshal(jsonData, v) } // MarshalJSON encodes EmbeddedJSON to a JSON object. func (v EmbeddedJSON) MarshalJSON() ([]byte, error) { return json.Marshal(v.any) } // UnmarshalJSON decodes a JSON object. func (v *EmbeddedJSON) UnmarshalJSON(b []byte) error { dec := json.NewDecoder(bytes.NewReader(b)) dec.UseNumber() return dec.Decode(&v.any) } func Example_embeddedJSONTagForCBOR() { value := NewEmbeddedJSON(map[string]any{ "name": "gopher", "id": json.Number("42"), }) data, err := cbor.Marshal(value) if err != nil { panic(err) } fmt.Printf("cbor: %x\n", data) var v EmbeddedJSON err = cbor.Unmarshal(data, &v) if err != nil { panic(err) } ``` -------------------------------- ### String Trim Example Source: https://github.com/carvel-dev/kapp-controller/blob/develop/vendor/github.com/google/cel-go/ext/README.md Demonstrates removing leading and trailing whitespace from a string. ```cel ' trim '.trim() // returns 'trim' ``` -------------------------------- ### TransformMap Map Value Example Source: https://github.com/carvel-dev/kapp-controller/blob/develop/vendor/github.com/google/cel-go/ext/README.md Transforms the values of a map by appending a character to each value. ```cel {'greeting': 'hello'}.transformMap(k, v, v + '!') ``` -------------------------------- ### TransformList Map Values Example Source: https://github.com/carvel-dev/kapp-controller/blob/develop/vendor/github.com/google/cel-go/ext/README.md Transforms a map into a list containing only the values of the map. ```cel {'greeting': 'hello', 'farewell': 'goodbye'} .transformList(_, v, v) ``` -------------------------------- ### Run Kapp-Controller Benchmark Tests Locally Source: https://github.com/carvel-dev/kapp-controller/blob/develop/docs/dev.md Run benchmark tests locally using the go toolchain. Benchmark results are also graphed on GitHub pages. ```bash go test ./test/bench/... -bench=. ``` -------------------------------- ### TransformList Map Keys Example Source: https://github.com/carvel-dev/kapp-controller/blob/develop/vendor/github.com/google/cel-go/ext/README.md Transforms a map into a list containing only the keys of the map. ```cel {'greeting': 'hello', 'farewell': 'goodbye'} .transformList(k, _, k) ``` -------------------------------- ### Run Standard Tests Source: https://github.com/carvel-dev/kapp-controller/blob/develop/vendor/google.golang.org/grpc/CONTRIBUTING.md Execute the Go tests with specified CPU configurations and timeout. ```bash go test -cpu 1,4 -timeout 7m ./... ```