### Install go.yaml.in/yaml/v3 Source: https://github.com/kubevirt/ssp-operator/blob/main/vendor/go.yaml.in/yaml/v3/README.md Use 'go get' to install the package. The import path is go.yaml.in/yaml/v3. ```bash go get go.yaml.in/yaml/v3 ``` -------------------------------- ### Install Backoff Library Source: https://github.com/kubevirt/ssp-operator/blob/main/vendor/github.com/jpillora/backoff/README.md Install the backoff library using the go get command. ```bash $ go get -v github.com/jpillora/backoff ``` -------------------------------- ### Install Zap Logging Library Source: https://github.com/kubevirt/ssp-operator/blob/main/vendor/go.uber.org/zap/README.md Use go get to install the Zap library. Zap supports the two most recent minor versions of Go. ```bash go get -u go.uber.org/zap ``` -------------------------------- ### Install and Import kubernetes-sigs/yaml Source: https://github.com/kubevirt/ssp-operator/blob/main/vendor/sigs.k8s.io/yaml/README.md Install the package using go get and import it using the standard import path. ```bash $ go get sigs.k8s.io/yaml ``` ```go import "sigs.k8s.io/yaml" ``` -------------------------------- ### Install Ginkgo Locally Source: https://github.com/kubevirt/ssp-operator/blob/main/vendor/github.com/onsi/ginkgo/v2/CONTRIBUTING.md Installs the Ginkgo binary locally using go install. Ensure you have Go installed and configured. ```bash go install ./... ``` -------------------------------- ### Initialize Procfs and Get Stat Source: https://github.com/kubevirt/ssp-operator/blob/main/vendor/github.com/prometheus/procfs/README.md Initializes the proc filesystem and retrieves CPU statistics. Use this to get started with basic system metrics. ```go fs, err := procfs.NewFS("/proc") stats, err := fs.Stat() ``` -------------------------------- ### Install Cobra Library Source: https://github.com/kubevirt/ssp-operator/blob/main/vendor/github.com/spf13/cobra/README.md Install the latest version of the Cobra library using go get. ```bash go get -u github.com/spf13/cobra@latest ``` -------------------------------- ### Install json-iterator/go Source: https://github.com/kubevirt/ssp-operator/blob/main/api/vendor/github.com/json-iterator/go/README.md Use go get to install the json-iterator/go package. ```go go get github.com/json-iterator/go ``` -------------------------------- ### Ginkgo Spec Example Source: https://github.com/kubevirt/ssp-operator/blob/main/vendor/github.com/onsi/ginkgo/v2/README.md This is a comprehensive example of a Ginkgo test suite for a library system. It showcases setup with BeforeEach, conditional logic with When and Context, and assertions with It and Gomega matchers. Use this as a template for structuring your own Ginkgo tests. ```go import ( . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ... ) var _ = Describe("Checking books out of the library", Label("library"), func() { var library *libraries.Library var book *books.Book var valjean *users.User BeforeEach(func() { library = libraries.NewClient() book = &books.Book{ Title: "Les Miserables", Author: "Victor Hugo", } valjean = users.NewUser("Jean Valjean") }) When("the library has the book in question", func() { BeforeEach(func(ctx SpecContext) { Expect(library.Store(ctx, book)).To(Succeed()) }) Context("and the book is available", func() { It("lends it to the reader", func(ctx SpecContext) { Expect(valjean.Checkout(ctx, library, "Les Miserables")).To(Succeed()) Expect(valjean.Books()).To(ContainElement(book)) Expect(library.UserWithBook(ctx, book)).To(Equal(valjean)) }, SpecTimeout(time.Second * 5)) }) Context("but the book has already been checked out", func() { var javert *users.User BeforeEach(func(ctx SpecContext) { javert = users.NewUser("Javert") Expect(javert.Checkout(ctx, library, "Les Miserables")).To(Succeed()) }) It("tells the user", func(ctx SpecContext) { err := valjean.Checkout(ctx, library, "Les Miserables") Expect(err).To(MatchError("Les Miserables is currently checked out")) }, SpecTimeout(time.Second * 5)) It("lets the user place a hold and get notified later", func(ctx SpecContext) { Expect(valjean.Hold(ctx, library, "Les Miserables")).To(Succeed()) Expect(valjean.Holds(ctx)).To(ContainElement(book)) By("when Javert returns the book") Expect(javert.Return(ctx, library, book)).To(Succeed()) By("it eventually informs Valjean") notification := "Les Miserables is ready for pick up" Eventually(ctx, valjean.Notifications).Should(ContainElement(notification)) Expect(valjean.Checkout(ctx, library, "Les Miserables")).To(Succeed()) Expect(valjean.Books(ctx)).To(ContainElement(book)) Expect(valjean.Holds(ctx)).To(BeEmpty()) }, SpecTimeout(time.Second * 10)) }) }) When("the library does not have the book in question", func() { It("tells the reader the book is unavailable", func(ctx SpecContext) { err := valjean.Checkout(ctx, library, "Les Miserables") Expect(err).To(MatchError("Les Miserables is not in the library catalog")) }, SpecTimeout(time.Second * 5)) }) }) ``` -------------------------------- ### Install multierr Source: https://github.com/kubevirt/ssp-operator/blob/main/vendor/go.uber.org/multierr/README.md Install the latest version of the multierr package using go get. ```bash go get -u go.uber.org/multierr@latest ``` -------------------------------- ### Install google/uuid Package Source: https://github.com/kubevirt/ssp-operator/blob/main/vendor/github.com/google/uuid/README.md Use this command to install the uuid package using go get. ```sh go get github.com/google/uuid ``` -------------------------------- ### Preview Documentation Changes Source: https://github.com/kubevirt/ssp-operator/blob/main/vendor/github.com/onsi/ginkgo/v2/CONTRIBUTING.md Builds and serves the Ginkgo documentation locally using Jekyll. This command requires Bundler to be installed. ```bash bundle && bundle exec jekyll serve ``` -------------------------------- ### Define a WebService and a GET Route Source: https://github.com/kubevirt/ssp-operator/blob/main/vendor/github.com/emicklei/go-restful/v3/README.md Example of defining a WebService with path, consumes, and produces types, and adding a GET route to find a user by ID. The route specifies documentation, a path parameter, and the expected response type. ```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 go-openapi/jsonreference Source: https://github.com/kubevirt/ssp-operator/blob/main/vendor/github.com/go-openapi/jsonreference/README.md Use this command to add the jsonreference library to your Go project. ```cmd go get github.com/go-openapi/jsonreference ``` -------------------------------- ### Registering Webhooks in main.go (Go) Source: https://context7.com/kubevirt/ssp-operator/llms.txt Example of how to set up the webhook manager in the main application file. Ensure the ENABLE_WEBHOOKS environment variable is not set to 'false'. ```go // Register webhooks in main.go: // if os.Getenv("ENABLE_WEBHOOKS") != "false" { // if err = webhooks.Setup(mgr); err != nil { // setupLog.Error(err, "unable to create webhook") // os.Exit(1) // } // } ``` -------------------------------- ### Install and Use Pre-commit Hooks Source: https://github.com/kubevirt/ssp-operator/blob/main/docs/development.md Installs the pre-commit tool and configures Git to use it for catching simple mistakes before committing. ```shell pip install --user pre-commit ``` ```shell pre-commit install ``` ```shell git commit -s ``` -------------------------------- ### Install jsonpointer Go Library Source: https://github.com/kubevirt/ssp-operator/blob/main/vendor/github.com/go-openapi/jsonpointer/README.md Use this command to add the jsonpointer library to your Go project. ```cmd go get github.com/go-openapi/jsonpointer ``` -------------------------------- ### Simple Backoff Example Source: https://github.com/kubevirt/ssp-operator/blob/main/vendor/github.com/jpillora/backoff/README.md Demonstrates the basic usage of the backoff counter, including setting min, max, factor, and jitter, and how Reset() affects the duration. ```go b := &backoff.Backoff{ //These are the defaults Min: 100 * time.Millisecond, Max: 10 * time.Second, Factor: 2, Jitter: false, } fmt.Printf("%s\n", b.Duration()) fmt.Printf("%s\n", b.Duration()) fmt.Printf("%s\n", b.Duration()) fmt.Printf("Reset!\n") b.Reset() fmt.Printf("%s\n", b.Duration()) ``` -------------------------------- ### Install jwt-go Package Source: https://github.com/kubevirt/ssp-operator/blob/main/vendor/github.com/golang-jwt/jwt/v5/README.md Use this command to add jwt-go as a dependency in your Go program. Ensure you have Go installed. ```sh go get -u github.com/golang-jwt/jwt/v5 ``` -------------------------------- ### Coexist with glog Source: https://github.com/kubevirt/ssp-operator/blob/main/api/vendor/k8s.io/klog/v2/README.md Example demonstrating how to initialize and synchronize flags between klog and glog. It also shows how to set alsologtostderr to true for combined stderr output. ```go package main import ( flag "flag" "k8s.io/klog/v2" "github.com/golang/glog" ) func main() { // Initialize klog flags klog.InitFlags(nil) // Initialize glog flags flag.Parse() // Set alsologtostderr to true for combined stderr output klog.SetLogger(glog.NewGlogr()) klog.SetOutput(os.Stderr) klog.Info("klog and glog coexisting") glog.Info("glog message") } ``` -------------------------------- ### PromQL Query Label Selectivity Example Source: https://github.com/kubevirt/ssp-operator/blob/main/docs/monitoring-guidelines.md When creating PromQL queries, prefer selecting by minimum required labels to avoid issues with changing label sets. This example shows preferring `sum by (namespace)` over a more exhaustive `sum by (namespace,pod,container,instance)`. ```promql sum by (namespace)(...) ``` ```promql sum by (namespace,pod,container,instance)(...) ``` -------------------------------- ### Setup Zap Repository Source: https://github.com/kubevirt/ssp-operator/blob/main/vendor/go.uber.org/zap/CONTRIBUTING.md Clone the zap repository and set up remote upstream for contributing. Ensure your local environment is configured correctly. ```bash mkdir -p $GOPATH/src/go.uber.org cd $GOPATH/src/go.uber.org git clone git@github.com:your_github_username/zap.git cd zap git remote add upstream https://github.com/uber-go/zap.git git fetch upstream ``` -------------------------------- ### Basic WebService Definition and Route Source: https://github.com/kubevirt/ssp-operator/blob/main/vendor/github.com/emicklei/go-restful/v3/README.md Demonstrates how to define a WebService with a specific path, supported content types, and a GET route for retrieving a user. ```APIDOC ## GET /users/{user-id} ### Description Retrieves a user resource based on the provided user identifier. ### Method GET ### Endpoint /users/{user-id} #### Path Parameters - **user-id** (string) - Required - The unique identifier of the user to retrieve. ### Request Example (No request body for GET) ### Response #### Success Response (200) - **User{}** (object) - Represents the user resource. #### Response Example (Example response body would be a User object, e.g., `{"id": "123", "name": "John Doe"}`) ``` -------------------------------- ### Add or Update Dependency Source: https://github.com/kubevirt/ssp-operator/blob/main/vendor/github.com/prometheus/procfs/CONTRIBUTING.md Use 'go get' to add or update external packages. Dependencies are vendored in 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 ``` -------------------------------- ### Debug Logging with V(1) Source: https://github.com/kubevirt/ssp-operator/blob/main/vendor/sigs.k8s.io/controller-runtime/TMP-LOGGING.md Example of using the V(1) method to log debug information with associated context. ```go logger.V(1).Info("this is particularly verbose!", "state of the world", allKubernetesObjectsEverywhere) ``` -------------------------------- ### Basic Test Script Syntax Source: https://github.com/kubevirt/ssp-operator/blob/main/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md Example of a test case script format. Comments are supported with '#'. All operations occur in a temporary directory. ```bash # Create a new empty file with some data. watch / echo data >/file Output: create /file write /file ``` -------------------------------- ### Backoff with Jitter Example Source: https://github.com/kubevirt/ssp-operator/blob/main/vendor/github.com/jpillora/backoff/README.md Illustrates how to enable and use jitter for randomized backoff durations. Seeding the random number generator is optional but provides repeatable results. ```go import "math/rand" b := &backoff.Backoff{ Jitter: true, } rand.Seed(42) fmt.Printf("%s\n", b.Duration()) fmt.Printf("%s\n", b.Duration()) fmt.Printf("%s\n", b.Duration()) fmt.Printf("Reset!\n") b.Reset() fmt.Printf("%s\n", b.Duration()) fmt.Printf("%s\n", b.Duration()) fmt.Printf("%s\n", b.Duration()) ``` -------------------------------- ### Run Golang CI Linter Source: https://github.com/kubevirt/ssp-operator/blob/main/docs/development.md Installs golangci-lint if not present and runs the linter. This target is also used when running unit tests locally. ```shell make lint ``` -------------------------------- ### VirtualMachine with Validator Annotation (YAML) Source: https://context7.com/kubevirt/ssp-operator/llms.txt Example of a VirtualMachine resource with a 'vm.kubevirt.io/validations' annotation. This annotation specifies validation rules for the VM's CPU cores. ```yaml # Example VM with validator annotation: # apiVersion: kubevirt.io/v1 # kind: VirtualMachine # metadata: # name: my-vm # annotations: # vm.kubevirt.io/validations: | # [{"name":"min-cpu","path":"spec.domain.cpu.cores","rule":"integer","min":1}] # spec: ... ``` -------------------------------- ### Zap Logger Quick Start Source: https://github.com/kubevirt/ssp-operator/blob/main/vendor/go.uber.org/zap/README.md Use Logger when performance and type safety are critical. It is faster than SugaredLogger and allocates less, supporting only structured logging. ```go logger, _ := zap.NewProduction() defer logger.Sync() logger.Info("failed to fetch URL", // Structured context as strongly typed Field values. zap.String("url", url), zap.Int("attempt", 3), zap.Duration("backoff", time.Second), ) ``` -------------------------------- ### SpdyStream Client Example Source: https://github.com/kubevirt/ssp-operator/blob/main/vendor/github.com/moby/spdystream/README.md Demonstrates how to establish a client connection to a SPDY server, create a stream, write data to it, read data back, and close the stream. Requires a running SPDY server on localhost:8080. ```go package main import ( "fmt" "github.com/moby/spdystream" "net" "net/http" ) func main() { conn, err := net.Dial("tcp", "localhost:8080") if err != nil { panic(err) } spdyConn, err := spdystream.NewConnection(conn, false) if err != nil { panic(err) } go spdyConn.Serve(spdystream.NoOpStreamHandler) stream, err := spdyConn.CreateStream(http.Header{}, nil, false) if err != nil { panic(err) } stream.Wait() fmt.Fprint(stream, "Writing to stream") buf := make([]byte, 25) stream.Read(buf) fmt.Println(string(buf)) stream.Close() } ``` -------------------------------- ### Install CRDs and Run Operator Locally Source: https://github.com/kubevirt/ssp-operator/blob/main/docs/development.md Installs Custom Resource Definitions (CRDs) to the cluster and starts the operator locally. Webhooks are disabled by default when running locally. ```shell make install make run ENABLE_WEBHOOKS=false ``` -------------------------------- ### Basic Structured Logging vs Standard Library Source: https://github.com/kubevirt/ssp-operator/blob/main/vendor/sigs.k8s.io/controller-runtime/TMP-LOGGING.md Illustrates the difference between standard library logging and controller-runtime's structured logging for a common scenario. ```go log.Printf("starting reconciliation for pod %s/%s", podNamespace, podName) ``` ```go logger.Info("starting reconciliation", "pod", req.NamespacedName) ``` -------------------------------- ### Install Latest JSON-Patch v5 Source: https://github.com/kubevirt/ssp-operator/blob/main/vendor/gopkg.in/evanphx/json-patch.v4/README.md Use this command to get the latest version of the json-patch library. ```bash go get -u github.com/evanphx/json-patch/v5 ``` -------------------------------- ### Get/Set Interface{} Value with reflect2 Source: https://github.com/kubevirt/ssp-operator/blob/main/api/vendor/github.com/modern-go/reflect2/README.md To get and set values of an interface{}, always use its pointer. This example demonstrates setting a variable's value using its type information. ```go valType := reflect2.TypeOf(1) i := 1 j := 10 valType.Set(&i, &j) // i will be 10 ``` -------------------------------- ### Create Root Logger Source: https://github.com/kubevirt/ssp-operator/blob/main/api/vendor/github.com/go-logr/logr/README.md Initialize the root logger early in the application's lifecycle. This example shows creating a logger using a hypothetical 'logimpl' implementation with initial parameters. ```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 ... } ``` -------------------------------- ### Example using TagSet and TagOptions Source: https://github.com/kubevirt/ssp-operator/blob/main/api/vendor/github.com/fxamacker/cbor/v2/README.md Shows how to create a TagSet, register a custom tag (COSE_Sign1 18) with a specific Go type, and then use this TagSet to create decoding and encoding modes for handling tagged CBOR data. ```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(t 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/kubevirt/ssp-operator/blob/main/vendor/github.com/spf13/cobra/README.md Install the cobra-cli tool, which generates Cobra application scaffolding. ```bash go install github.com/spf13/cobra-cli@latest ``` -------------------------------- ### Install SSP Operator Manually Source: https://context7.com/kubevirt/ssp-operator/llms.txt Manually install the SSP Operator by applying its YAML manifest. This method is useful for direct deployment or when using specific versions. ```shell # Install CRDs and deploy the latest released version manually: export SSP_VERSION=$(curl -s https://api.github.com/repos/kubevirt/ssp-operator/releases/latest \ | jq -r '.name') oc apply -f https://github.com/kubevirt/ssp-operator/releases/download/${SSP_VERSION}/ssp-operator.yaml ``` -------------------------------- ### SpdyStream Server Example Source: https://github.com/kubevirt/ssp-operator/blob/main/vendor/github.com/moby/spdystream/README.md Provides a basic SPDY server implementation that listens for incoming TCP connections on localhost:8080 and serves mirrored streams using MirrorStreamHandler. Handles multiple client connections concurrently. ```go package main import ( "github.com/moby/spdystream" "net" ) func main() { listener, err := net.Listen("tcp", "localhost:8080") if err != nil { panic(err) } for { conn, err := listener.Accept() if err != nil { panic(err) } spdyConn, err := spdystream.NewConnection(conn, true) if err != nil { panic(err) } go spdyConn.Serve(spdystream.MirrorStreamHandler) } } ``` -------------------------------- ### Install Latest SSP Operator Version Source: https://github.com/kubevirt/ssp-operator/blob/main/docs/installation.md Fetches the latest SSP operator version and applies its manifest to the cluster. Ensure you have `oc` and `jq` installed and configured. ```shell export SSP_VERSION=$(curl https://api.github.com/repos/kubevirt/ssp-operator/releases/latest | jq '.name' | tr -d '"') oc apply -f https://github.com/kubevirt/ssp-operator/releases/download/${SSP_VERSION}/ssp-operator.yaml ``` -------------------------------- ### Apply JSON Patches via CLI Source: https://github.com/kubevirt/ssp-operator/blob/main/vendor/gopkg.in/evanphx/json-patch.v4/README.md Applies one or more JSON patch files to a JSON document provided via stdin using the `json-patch` command-line tool. Install with `go install github.com/evanphx/json-patch/cmd/json-patch`. ```json [ {"op": "replace", "path": "/name", "value": "Jane"}, {"op": "remove", "path": "/height"} ] ``` ```json [ {"op": "add", "path": "/address", "value": "123 Main St"}, {"op": "replace", "path": "/age", "value": "21"} ] ``` ```json { "name": "John", "age": 24, "height": 3.21 } ``` ```bash $ go install github.com/evanphx/json-patch/cmd/json-patch $ cat document.json | json-patch -p patch.1.json -p patch.2.json {"address":"123 Main St","age":"21","name":"Jane"} ``` -------------------------------- ### Example: Embedded JSON Tag for CBOR (tag 262) Source: https://github.com/kubevirt/ssp-operator/blob/main/vendor/github.com/fxamacker/cbor/v2/README.md Implement MarshalCBOR and UnmarshalCBOR to handle CBOR tag number 262, which embeds a JSON object as a CBOR byte string. This example demonstrates encoding and decoding such a tagged item. ```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) } ``` -------------------------------- ### Create and Resolve JSON References in Go Source: https://github.com/kubevirt/ssp-operator/blob/main/vendor/github.com/go-openapi/jsonreference/README.md Demonstrates how to create new JSON references from strings, create fragment-only references, and resolve references by inheriting a base URI. ```go // Creating a new reference ref, err := jsonreference.New("http://example.com/doc.json#/definitions/Pet") // Fragment-only reference fragRef := jsonreference.MustCreateRef("#/definitions/Pet") // Resolving references parent, _ := jsonreference.New("http://example.com/base.json") child, _ := jsonreference.New("#/definitions/Pet") resolved, _ := parent.Inherits(child) // Result: "http://example.com/base.json#/definitions/Pet" ``` -------------------------------- ### Basic fsnotify Watcher Usage in Go Source: https://github.com/kubevirt/ssp-operator/blob/main/vendor/github.com/fsnotify/fsnotify/README.md Demonstrates how to create a new watcher, listen for events and errors in a separate goroutine, add a directory to watch, and handle potential errors. Ensure the watcher's channels are read in a goroutine to avoid blocking. ```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{}) } ``` -------------------------------- ### Import jwt-go Package Source: https://github.com/kubevirt/ssp-operator/blob/main/vendor/github.com/golang-jwt/jwt/v5/README.md Import the jwt package into your Go code after installation. ```go import "github.com/golang-jwt/jwt/v5" ``` -------------------------------- ### Script Comments Source: https://github.com/kubevirt/ssp-operator/blob/main/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md Demonstrates comment syntax within a script. Comments start with '#'. ```bash # Comment cmd arg arg # Comment ``` -------------------------------- ### Basic Logr Usage with Zapr Source: https://github.com/kubevirt/ssp-operator/blob/main/vendor/github.com/go-logr/zapr/README.md Demonstrates how to initialize a zap logger and use it with the logr interface. Ensure zap is imported for logger creation and zapr for the logr implementation. ```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) } ``` -------------------------------- ### Install JSON-Patch v4 Source: https://github.com/kubevirt/ssp-operator/blob/main/vendor/gopkg.in/evanphx/json-patch.v4/README.md Use this command if you specifically need version 4 of the json-patch library. ```bash go get -u gopkg.in/evanphx/json-patch.v4 ``` -------------------------------- ### xxhash v2 Benchmarking Commands Source: https://github.com/kubevirt/ssp-operator/blob/main/vendor/github.com/cespare/xxhash/v2/README.md These commands demonstrate how to run benchmarks for the pure Go and assembly implementations of the `Sum64` function using `benchstat`. ```bash benchstat <(go test -tags purego -benchtime 500ms -count 15 -bench 'Sum64$') ``` ```bash benchstat <(go test -benchtime 500ms -count 15 -bench 'Sum64$') ``` -------------------------------- ### Retrieving a Value Source: https://github.com/kubevirt/ssp-operator/blob/main/vendor/github.com/go-openapi/jsonpointer/README.md Demonstrates how to use the `Get` method to retrieve a value from a JSON document using a JSON Pointer. ```APIDOC import ( "github.com/go-openapi/jsonpointer" ) var doc any ... pointer, err := jsonpointer.New("/foo/1") if err != nil { ... // error: e.g. invalid JSON pointer specification } value, kind, err := pointer.Get(doc) if err != nil { ... // error: e.g. key not found, index out of bounds, etc. } ... ``` -------------------------------- ### Basic glog Usage Source: https://github.com/kubevirt/ssp-operator/blob/main/api/vendor/k8s.io/klog/v2/README.md Demonstrates basic Info and Fatalf logging functions. Use Fatalf for critical errors that should stop execution. ```go glog.Info("Prepare to repel boarders") ``` ```go glog.Fatalf("Initialization failed: %s", err) ``` -------------------------------- ### Caller Reporting Text Output Source: https://github.com/kubevirt/ssp-operator/blob/main/vendor/github.com/sirupsen/logrus/README.md Example text output when caller reporting is enabled, including the 'method' field. ```text time="2015-03-26T01:27:38-04:00" level=fatal method=github.com/sirupsen/arcticcreatures.migrate msg="a penguin swims by" animal=penguin ```