### Basic Echo Server Setup Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/vendor/github.com/labstack/echo/v4/README.md A minimal example demonstrating how to create an Echo instance, apply logger and recover middleware, define a root route, and start the HTTP server. ```go package main import ( "github.com/labstack/echo/v4" "github.com/labstack/echo/v4/middleware" "log/slog" "net/http" "errors" ) func main() { // Echo instance e := echo.New() // Middleware e.Use(middleware.Logger()) e.Use(middleware.Recover()) // Routes e.GET("/", hello) // Start server if err := e.Start(":8080"); err != nil && !errors.Is(err, http.ErrServerClosed) { slog.Error("failed to start server", "error", err) } } // Handler func hello(c echo.Context) error { return c.String(http.StatusOK, "Hello, World!") } ``` -------------------------------- ### Install go.yaml.in/yaml/v2 Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/vendor/go.yaml.in/yaml/v2/README.md Use 'go get' to install the package. This command fetches and installs the specified package and its dependencies. ```bash go get go.yaml.in/yaml/v2 ``` -------------------------------- ### Install go-isatty Package Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/vendor/github.com/mattn/go-isatty/README.md Install the go-isatty package using the go get command. ```bash $ go get github.com/mattn/go-isatty ``` -------------------------------- ### Install Mergo Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/vendor/dario.cat/mergo/README.md Install the Mergo library using go get. ```go go get dario.cat/mergo ``` -------------------------------- ### Install Echo Framework Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/vendor/github.com/labstack/echo/v4/README.md Use `go get` to install the Echo framework. Ensure you are using a compatible Go version. ```sh go get github.com/labstack/echo/v4 ``` -------------------------------- ### Install and Import YAML Library Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/vendor/github.com/ghodss/yaml/README.md Instructions for installing the library using go get and importing it into your Go project. ```bash go get github.com/ghodss/yaml ``` ```go import "github.com/ghodss/yaml" ``` -------------------------------- ### Example Configuration File Content Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/docs/functest-container.md This is an example of the YAML content for the test configuration file, specifying quick start test items. ```yaml quickStart: testItems: - name: test-quick-start displayName: Test Quickstart Tour ``` -------------------------------- ### Install Lamenv Go Library Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/vendor/github.com/nexucis/lamenv/README.md Use standard go get to install the lamenv library. ```bash go get github.com/nexucis/lamenv ``` -------------------------------- ### Full Mux Server Example Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/tools/digester/vendor/github.com/gorilla/mux/README.md A complete, runnable example of a basic HTTP server using Gorilla Mux. It sets up a single route and handler, then starts listening on a specified port. ```go package main import ( "net/http" "log" "github.com/gorilla/mux" ) func YourHandler(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Gorilla!\n")) } func main() { r := mux.NewRouter() // Routes consist of a path and a handler function. r.HandleFunc("/", YourHandler) // Bind to a port and pass our router in log.Fatal(http.ListenAndServe(":8000", r)) } ``` -------------------------------- ### Install gommon/color Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/vendor/github.com/labstack/gommon/color/README.md Install the gommon/color package using go get. ```sh go get github.com/labstack/gommon/color ``` -------------------------------- ### Basic WebService Setup and Route Definition Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/vendor/github.com/emicklei/go-restful/v3/README.md Demonstrates how to initialize a WebService, set its path and content types, and define a GET route for retrieving a user by ID. ```APIDOC ## GET /users/{user-id} ### Description Retrieves a user resource based on the provided user ID. ### Method GET ### Endpoint /users/{user-id} ### Parameters #### Path Parameters - **user-id** (string) - Required - The unique identifier of the user to retrieve. ### Request Example (No request body for GET requests) ### Response #### Success Response (200) - **User{}** - Represents the user object if found. ### Response Example (Example response body would be a User object, e.g., `{"id": "123", "name": "John Doe"}`) ``` -------------------------------- ### Install multierr Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/vendor/go.uber.org/multierr/README.md Use `go get` to install the latest version of the multierr package. ```bash go get -u go.uber.org/multierr@latest ``` -------------------------------- ### Install and import the YAML package Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/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 Flect Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/vendor/github.com/gobuffalo/flect/README.md Use 'go get' to install the Flect package for your Go project. ```console go get github.com/gobuffalo/flect ``` -------------------------------- ### Install json-iterator/go Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/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 jsonpointer Library Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/vendor/github.com/go-openapi/jsonpointer/README.md Use 'go get' to add the jsonpointer library to your project. ```bash go get github.com/go-openapi/jsonpointer ``` -------------------------------- ### Install gorilla/mux Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/tools/digester/vendor/github.com/gorilla/mux/README.md Install the gorilla/mux package using the go get command. Ensure your Go toolchain is correctly configured. ```sh go get -u github.com/gorilla/mux ``` -------------------------------- ### Python Virtual Environment Setup Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/tools/k8s-label-visualizer/README.md Sets up a Python virtual environment and installs project dependencies. ```bash python3 -m venv ./venv source ./venv/bin/activate pip3 install -r requirements.txt ``` -------------------------------- ### CLI Example: Allow Post-Copy Migrations Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/docs/cluster-configuration-v1-api.md Demonstrates enabling and then disabling post-copy migrations via `kubectl annotate` and verifying the change with `kubectl get` and `jq`. It also shows how to check for unsupported feature annotations. ```bash $ kubectl annotate --overwrite -n kubevirt-hyperconverged hco kubevirt-hyperconverged \ kubevirt.kubevirt.io/jsonpatch='[{"op": "add", \ "path": "/spec/configuration/migrations", \ "value": {"allowPostCopy": true} }]' hyperconverged.hco.kubevirt.io/kubevirt-hyperconverged annotated $ kubectl get kubevirt -n kubevirt-hyperconverged kubevirt-kubevirt-hyperconverged -o json \ | jq '.spec.configuration.migrations.allowPostCopy' true $ kubectl annotate --overwrite -n kubevirt-hyperconverged hco kubevirt-hyperconverged \ kubevirt.kubevirt.io/jsonpatch='[{"op": "add", \ "path": "/spec/configuration/migrations", \ "value": {"allowPostCopy": false} }]' hyperconverged.hco.kubevirt.io/kubevirt-hyperconverged annotated $ kubectl get kubevirt -n kubevirt-hyperconverged kubevirt-kubevirt-hyperconverged -o json \ | jq '.spec.configuration.migrations.allowPostCopy' false $ kubectl get hco -n kubevirt-hyperconverged kubevirt-hyperconverged -o json \ | jq '.status.conditions[] | select(.type == "TaintedConfiguration")' { "lastHeartbeatTime": "2021-03-24T17:25:49Z", "lastTransitionTime": "2021-03-24T11:33:11Z", "message": "Unsupported feature was activated via an HCO annotation", "reason": "UnsupportedFeatureAnnotation", "status": "True", "type": "TaintedConfiguration" } ``` -------------------------------- ### ClusterInfo Initialization and Usage Example Source: https://context7.com/kubevirt/hyperconverged-cluster-operator/llms.txt Demonstrates how to initialize the ClusterInfo implementation and use its methods to conditionally enable OpenShift-specific controllers during reconciler setup. ```go // Usage in reconciler setup: ci := &hcoutil.ClusterInfoImp{} if err := ci.Init(ctx, cl, logger); err != nil { return err } if ci.IsOpenshift() { // register OpenShift-specific controllers (SSP, ConsoleCLIDownload, etc.) } ``` -------------------------------- ### Install uuid Package Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/vendor/github.com/google/uuid/README.md Use 'go get' to install the uuid package. This command fetches and installs the package and its dependencies. ```sh go get github.com/google/uuid ``` -------------------------------- ### Install go-colorable Package Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/vendor/github.com/mattn/go-colorable/README.md Install the go-colorable package using the go get command. This is a prerequisite for using the package in your Go projects. ```bash go get github.com/mattn/go-colorable ``` -------------------------------- ### Install Backoff Package Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/vendor/github.com/jpillora/backoff/README.md Install the backoff package using the go get command. ```bash $ go get -v github.com/jpillora/backoff ``` -------------------------------- ### Zap Installation Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/vendor/go.uber.org/zap/README.md Install Zap using go get. Note that Zap only supports the two most recent minor versions of Go. ```bash go get -u go.uber.org/zap ``` -------------------------------- ### Initialize Procfs and Get Stat Source: https://github.com/kubevirt/hyperconverged-cluster-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() ``` -------------------------------- ### Define a WebService with Routes Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/vendor/github.com/emicklei/go-restful/v3/README.md Example of creating a WebService, defining its path, supported content types, and a GET route for retrieving a user. The route specifies 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 lo Library Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/vendor/github.com/samber/lo/README.md Install the lo library using go get. This library is v1 and follows SemVer strictly, with no breaking changes to exported APIs before v2.0.0. ```sh go get github.com/samber/lo@v1 ``` -------------------------------- ### Install go.yaml.in/yaml/v3 Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/vendor/go.yaml.in/yaml/v3/README.md Run this command to install the YAML package for Go. The import path is go.yaml.in/yaml/v3. ```bash go get go.yaml.in/yaml/v3 ``` -------------------------------- ### Install go-pluralize Module Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/vendor/github.com/gertd/go-pluralize/README.md Use 'go get' to install the latest version of the go-pluralize module. To pin a specific version, append '@vX.Y.Z' to the command. ```bash go get -u github.com/gertd/go-pluralize ``` ```bash go get -u github.com/gertd/go-pluralize@v0.2.0 ``` -------------------------------- ### SpdyStream Server Example Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/vendor/github.com/moby/spdystream/README.md Provides a basic server implementation that listens for TCP connections, accepts them, and serves streams using the MirrorStreamHandler. ```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) } } ``` -------------------------------- ### Setup Zap Repository Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/vendor/go.uber.org/zap/CONTRIBUTING.md Clone the zap repository and set up upstream remote for contributing. ```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 ``` -------------------------------- ### Install Operator via operator-sdk Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/README.md Installs the operator using the 'operator-sdk run bundle' command. This is an alternative to deploying via OLM's CatalogSource. Ensure the correct namespace and bundle image reference are provided. ```bash operator-sdk run bundle -n --timeout=10m ``` -------------------------------- ### Install jwt-go package Source: https://github.com/kubevirt/hyperconverged-cluster-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 Go is installed first. ```sh go get -u github.com/golang-jwt/jwt/v5 ``` -------------------------------- ### JSONPath Example Package Gval Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/vendor/github.com/PaesslerAG/jsonpath/README.md This example demonstrates how to use JSONPath with Gval for advanced scripting features. Refer to the GoDoc for more details on combining JSONPath with script languages. ```go package main import ( "fmt" "github.com/PaesslerAG/jsonpath" "github.com/PaesslerAG/gval" ) func main() { var ( json = []byte(`{ "name": "John Doe", "age": 30, "isStudent": false, "courses": [ { "title": "Math", "credits": 3 }, { "title": "History", "credits": 4 } ] }`) ) // Example 1: Simple path query, _ := jsonpath.NewQuery("name") result, _ := query.Execute(json) fmt.Printf("\nName: %v\n", result) // Example 2: Path with array index query, _ = jsonpath.NewQuery("courses[0].title") result, _ = query.Execute(json) fmt.Printf("First course title: %v\n", result) // Example 3: Path with array length query, _ = jsonpath.NewQuery("courses[?(@.length > 3)].title") result, _ = query.Execute(json) fmt.Printf("Courses with more than 3 credits: %v\n", result) // Example 4: Path with regex query, _ = jsonpath.NewQuery("courses[?(@.title =~ \"^H.*\" )].title") result, _ = query.Execute(json) fmt.Printf("Courses starting with H: %v\n", result) // Example 5: Combine with Gval functions query, _ = jsonpath.NewQuery("courses[?(@.credits * 2 > 7)].title") result, _ = query.Execute(json) fmt.Printf("Courses where credits * 2 > 7: %v\n", result) // Example 6: Combine with Gval functions query, _ = jsonpath.NewQuery("courses[?(@.length(title) > 4)].title") result, _ = query.Execute(json) fmt.Printf("Courses with title length > 4: %v\n", result) } ``` -------------------------------- ### SpdyStream Client Example Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/vendor/github.com/moby/spdystream/README.md Demonstrates how to connect to a mirroring server, create a stream, write data, read data, and close the stream using SpdyStream. ```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 go-pluralize CLI Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/vendor/github.com/gertd/go-pluralize/README.md Install the command-line interface for go-pluralize using 'go get -x'. This allows you to perform pluralization operations directly from your terminal. ```bash go get -x github.com/gertd/go-pluralize/cmd/pluralize ``` -------------------------------- ### Apply KVM Emulation Overlay Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/deploy/kustomize/README.md Apply the kustomize overlay for KVM emulation to add the Subscription resource with relevant KVM configuration. ```bash $ oc apply -k kvm_emulation ``` -------------------------------- ### Install Latest JSON-Patch Source: https://github.com/kubevirt/hyperconverged-cluster-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 for Go. ```bash go get -u github.com/evanphx/json-patch/v5 ``` -------------------------------- ### Register Routes and Walk Router Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/tools/digester/vendor/github.com/gorilla/mux/README.md Demonstrates how to register various routes with different methods, query parameters, and path variables, and then iterate through all registered routes using the Walk function. ```go package main import ( "fmt" "net/http" "strings" "github.com/gorilla/mux" ) func handler(w http.ResponseWriter, r *http.Request) { return } func main() { r := mux.NewRouter() r.HandleFunc("/", handler) r.HandleFunc("/products", handler).Methods("POST") r.HandleFunc("/articles", handler).Methods("GET") r.HandleFunc("/articles/{id}", handler).Methods("GET", "PUT") r.HandleFunc("/authors", handler).Queries("surname", "{surname}") err := r.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error { pathTemplate, err := route.GetPathTemplate() if err == nil { fmt.Println("ROUTE:", pathTemplate) } pathRegexp, err := route.GetPathRegexp() if err == nil { fmt.Println("Path regexp:", pathRegexp) } queriesTemplates, err := route.GetQueriesTemplates() if err == nil { fmt.Println("Queries templates:", strings.Join(queriesTemplates, ",")) } queriesRegexps, err := route.GetQueriesRegexp() if err == nil { fmt.Println("Queries regexps:", strings.Join(queriesRegexps, ",")) } methods, err := route.GetMethods() if err == nil { fmt.Println("Methods:", strings.Join(methods, ",")) } fmt.Println() return nil }) if err != nil { fmt.Println(err) } http.Handle("/", r) } ``` -------------------------------- ### Expected Go Module Dependency Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/vendor/github.com/antlr4-go/antlr/v4/README.md This example illustrates the expected and desired way `go get` should resolve the ANTLR4 Go runtime version from its dedicated repository, providing clear and manageable versioning. ```go require ( github.com/antlr/antlr4/runtime/Go/antlr/v4 v4.13.0 ) ``` -------------------------------- ### Create Root Logger Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/vendor/github.com/go-logr/logr/README.md Create the root logger early in an application's lifecycle. This example shows initializing a logger with a specific implementation ('logimpl') and 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 ... } ``` -------------------------------- ### Incorrect Go Module Dependency Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/vendor/github.com/antlr4-go/antlr/v4/README.md This example shows how `go get` might resolve the ANTLR4 Go runtime version when it's embedded deeply within the main ANTLR4 repository, leading to unclear and difficult-to-manage versioning. ```go require ( github.com/antlr/antlr4/runtime/Go/antlr/v4 v4.0.0-20230219212500-1f9a474cc2dc ) ``` -------------------------------- ### Install Graphviz Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/tools/k8s-label-visualizer/README.md Installs the Graphviz package, which is a dependency for generating graphs. ```bash dnf install graphviz ``` -------------------------------- ### Basic Structured Logging vs. Standard Library Logging Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/vendor/sigs.k8s.io/controller-runtime/TMP-LOGGING.md Compares logging a reconciliation start event using the Go standard library's log.Printf with controller-runtime's structured logging approach. ```go log.Printf("starting reconciliation for pod %s/%s", podNamespace, podName) ``` ```go logger.Info("starting reconciliation", "pod", req.NamespacedName) ``` -------------------------------- ### Serving Static Files Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/tools/digester/vendor/github.com/gorilla/mux/README.md Serve static files from a directory using `PathPrefix` and `http.StripPrefix` with `http.FileServer`. Includes server setup with timeouts. ```go func main() { var dir string flag.StringVar(&dir, "dir", ".", "the directory to serve files from. Defaults to the current dir") flag.Parse() r := mux.NewRouter() // This will serve files under http://localhost:8000/static/ r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(dir)))) srv := &http.Server{ Handler: r, Addr: "127.0.0.1:8000", // Good practice: enforce timeouts for servers you create! WriteTimeout: 15 * time.Second, ReadTimeout: 15 * time.Second, } log.Fatal(srv.ListenAndServe()) } ``` -------------------------------- ### Install TOML Validator CLI Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/tools/digester/vendor/github.com/BurntSushi/toml/README.md Install the TOML validator command-line tool. Use it to validate TOML files. ```bash % go install github.com/BurntSushi/toml/cmd/tomlv@latest % tomlv some-toml-file.toml ``` -------------------------------- ### CPU Plugin Configurations Example Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/docs/cluster-configuration-v1-api.md Configure obsolete CPU models for the HyperConverged resource. This allows specifying a list of CPU models that are considered obsolete. ```yaml apiVersion: hco.kubevirt.io/v1 kind: HyperConverged metadata: name: kubevirt-hyperconverged spec: obsoleteCPUs: cpuModels: - "486" - "pentium" - "pentium2" - "pentium3" - "pentiumpro" ``` -------------------------------- ### Basic TOML Data Example Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/tools/digester/vendor/github.com/BurntSushi/toml/README.md Example of basic TOML data including integers, arrays, floats, and timestamps. ```toml Age = 25 Cats = [ "Cauchy", "Plato" ] Pi = 3.14 Perfection = [ 6, 28, 496, 8128 ] DOB = 1987-07-05T05:45:00Z ``` -------------------------------- ### Install Required Tools on RHEL8/CentOS8/Fedora Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/tools/mirror-csv-release/README.md Installs Podman, Skopeo, and Python3 using the dnf package manager. These are required for the mirroring process. ```bash sudo dnf install podman skopeo python3 ``` -------------------------------- ### Build URL with Host, Path, and Queries Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/tools/digester/vendor/github.com/gorilla/mux/README.md Construct a full URL including host, path, and query parameters from a named route. All variables, including host, path, and query parameters, must be provided. ```go r := mux.NewRouter() r.Host("{subdomain}.example.com"). Path("/articles/{category}/{id:[0-9]+}"). Queries("filter", "{filter}"). HandlerFunc(ArticleHandler). Name("article") // url.String() will be "http://news.example.com/articles/technology/42?filter=gorilla" url, err := r.Get("article").URL("subdomain", "news", "category", "technology", "id", "42", "filter", "gorilla") ``` -------------------------------- ### Simple Backoff Example Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/vendor/github.com/jpillora/backoff/README.md Demonstrates the basic usage of the backoff counter, including Duration() calls and Reset(). Defaults are used for Min, Max, Factor, and Jitter. ```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()) ``` -------------------------------- ### HCO Installation Methods Source: https://context7.com/kubevirt/hyperconverged-cluster-operator/llms.txt Lists the supported installation paths for the Hyperconverged Cluster Operator (HCO), including OLM/OperatorHub, kustomize, and direct script deployment. ```bash # HCO supports several installation paths: OLM/OperatorHub (recommended for production), kustomize (OpenShift), and direct `deploy.sh` (for non-OLM environments). ``` -------------------------------- ### HyperConverged CR Status Example Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/docs/cluster-configuration.md Example of the HyperConverged CR status field showing a DataImportCronTemplate with unsupported architectures for the current cluster and node information. ```yaml apiVersion: hco.kubevirt.io/v1beta1 kind: HyperConverged ... status: ... dataImportCronTemplates: - metadata: annotations: cdi.kubevirt.io/storage.bind.immediate.requested: "true" ssp.kubevirt.io/dict.architectures: "" name: my-image spec: ... status: conditions: - lastTransitionTime: "2025-07-09T11:00:30Z" message: DataImportCronTemplate has no supported architectures for the current cluster reason: UnsupportedArchitectures status: "False" type: Deployed originalSupportedArchitectures: someUnsupportedArch,otherUnsupportedArch ... nodeInfo: controlPlaneArchitectures: - amd64 workloadsArchitectures: - amd64 - arm64 ``` -------------------------------- ### Analyze CPU Profile with go tool pprof Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/docs/profiling.md Start CPU profiling by directing the `go tool pprof` command to the http endpoint. By default, it profiles for 30 seconds and displays the results. ```bash go tool pprof http://localhost:8070 ``` -------------------------------- ### Development Commands in Go Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/vendor/github.com/samber/lo/README.md Commands for setting up development dependencies and running tests within the project. ```bash # Install some dev dependencies make tools # Run tests make test # or make watch-test ``` -------------------------------- ### Install HCO via Kustomize Source: https://context7.com/kubevirt/hyperconverged-cluster-operator/llms.txt Installs the HCO using Kustomize, specifically for OpenShift OLM environments. This involves downloading the Kustomize deployment files and executing a deployment script. ```bash curl -L https://api.github.com/repos/kubevirt/hyperconverged-cluster-operator/tarball/main | \ tar --strip-components=1 -xvzf - kubevirt-hyperconverged-cluster-operator-*/deploy/kustomize ./deploy/kustomize/deploy_kustomize.sh ``` -------------------------------- ### Deploy HCO with Default Settings using Kustomize Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/deploy/kustomize/README.md Create a kustomization.yaml file to include base manifests and the namespace resource, then apply it to deploy HCO with default settings. ```bash cat <kustomization.yaml apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization bases: - base resources: - namespace.yaml EOF $ oc apply -k . ``` -------------------------------- ### Update Dependencies using go get and go mod tidy Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/vendor/github.com/golang-jwt/jwt/v5/MIGRATION_GUIDE.md After changing the import path, update your project dependencies using 'go get' and 'go mod tidy'. ```bash go get github.com/golang-jwt/jwt/v4 go mod tidy ``` -------------------------------- ### Set up Kubernetes Cluster with kubevirtci Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/docs/run-locally.md Use this command to set up a Kubernetes cluster using kubevirtci for local development. Ensure KUBECONFIG is set correctly afterwards. ```shell $ export KUBEVIRT_PROVIDER=k8s-1.17 $ make cluster-up ``` -------------------------------- ### Extract Substring Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/vendor/github.com/samber/lo/README.md Returns a portion of a string based on start index and length. Negative start indices are counted from the end of the string. `math.MaxUint` can be used for the length to extract until the end. ```go sub := lo.Substring("hello", 2, 3) // "llo" ``` ```go sub := lo.Substring("hello", -4, 3) // "ell" ``` ```go sub := lo.Substring("hello", -2, math.MaxUint) // "lo" ``` -------------------------------- ### Run All Unit Tests Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/docs/tests.md Execute all unit tests for the project. Ensure the KUBEVIRT_CLIENT_GO_SCHEME_REGISTRATION_VERSION environment variable is set to 'v1'. ```bash KUBEVIRT_CLIENT_GO_SCHEME_REGISTRATION_VERSION=v1 go test ./pkg/... ``` -------------------------------- ### Install HCO via OLM CatalogSource Source: https://context7.com/kubevirt/hyperconverged-cluster-operator/llms.txt Installs the HCO using an OLM CatalogSource for the latest unstable build. This method requires applying a CatalogSource, Namespace, OperatorGroup, and Subscription manifest. ```yaml apiVersion: operators.coreos.com/v1alpha1 kind: CatalogSource metadata: name: hco-unstable-catalog-source namespace: openshift-marketplace spec: sourceType: grpc image: quay.io/kubevirt/hyperconverged-cluster-index:1.19.0-unstable displayName: Kubevirt Hyperconverged Cluster Operator publisher: Kubevirt Project ``` ```yaml apiVersion: v1 kind: Namespace metadata: name: kubevirt-hyperconverged --- apiVersion: operators.coreos.com/v1 kind: OperatorGroup metadata: name: kubevirt-hyperconverged-group namespace: kubevirt-hyperconverged --- apiVersion: operators.coreos.com/v1alpha1 kind: Subscription metadata: name: hco-operatorhub namespace: kubevirt-hyperconverged spec: source: hco-unstable-catalog-source sourceNamespace: openshift-marketplace name: community-kubevirt-hyperconverged channel: "candidate-v1.19" ``` -------------------------------- ### Install HCO using kustomize Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/README.md Installs the default community HyperConverged Cluster Operator and its underlying components on OpenShift OLM. Deployment is complete when the HCO custom resource reports its condition as 'Available'. ```bash $ curl -L https://api.github.com/repos/kubevirt/hyperconverged-cluster-operator/tarball/main | \ tar --strip-components=1 -xvzf - kubevirt-hyperconverged-cluster-operator*/deploy/kustomize $ ./deploy/kustomize/deploy_kustomize.sh ``` -------------------------------- ### Basic Logr Usage with Zapr Source: https://github.com/kubevirt/hyperconverged-cluster-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) } ``` -------------------------------- ### Basic fsnotify Watcher Usage Source: https://github.com/kubevirt/hyperconverged-cluster-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 block the main goroutine. ```go package main import ( "log" "github.com/fsnotify/fsnotify" ) func main() { // Create new watcher. watcher, err := fsnotify.NewWatcher() if err != nil { log.Fatal(err) } defer watcher.Close() // Start listening for events. go func() { for { select { case event, ok := <-watcher.Events: if !ok { return } log.Println("event:", event) if event.Has(fsnotify.Write) { log.Println("modified file:", event.Name) } case err, ok := <-watcher.Errors: if !ok { return } log.Println("error:", err) } } }() // Add a path. err = watcher.Add("/tmp") if err != nil { log.Fatal(err) } // Block main goroutine forever. <-make(chan struct{}) } ``` -------------------------------- ### Enable Post-Copy Migrations via CLI Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/docs/cluster-configuration.md Use `kubectl annotate` to enable post-copy migrations. Verify the setting with `kubectl get kubevirt`. ```bash $kubectl annotate --overwrite -n kubevirt-hyperconverged hco kubevirt-hyperconverged \ kubevirt.kubevirt.io/jsonpatch='[{"op": "add", \ "path": "/spec/configuration/migrations", \ "value": {"allowPostCopy": true} }]' hyperconverged.hco.kubevirt.io/kubevirt-hyperconverged annotated $kubectl get kubevirt -n kubevirt-hyperconverged kubevirt-kubevirt-hyperconverged -o json \ | jq '.spec.configuration.migrations.allowPostCopy' true ``` ```bash $kubectl annotate --overwrite -n kubevirt-hyperconverged hco kubevirt-hyperconverged \ kubevirt.kubevirt.io/jsonpatch='[{"op": "add", \ "path": "/spec/configuration/migrations", \ "value": {"allowPostCopy": false} }]' hyperconverged.hco.kubevirt.io/kubevirt-hyperconverged annotated $kubectl get kubevirt -n kubevirt-hyperconverged kubevirt-kubevirt-hyperconverged -o json \ | jq '.spec.configuration.migrations.allowPostCopy' false ``` ```bash $kubectl get hco -n kubevirt-hyperconverged kubevirt-hyperconverged -o json \ | jq '.status.conditions[] | select(.type == "TaintedConfiguration")' { "lastHeartbeatTime": "2021-03-24T17:25:49Z", "lastTransitionTime": "2021-03-24T11:33:11Z", "message": "Unsupported feature was activated via an HCO annotation", "reason": "UnsupportedFeatureAnnotation", "status": "True", "type": "TaintedConfiguration" } ``` -------------------------------- ### Basic Logrus Usage with Fields Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/tools/digester/vendor/github.com/sirupsen/logrus/README.md Demonstrates the simplest way to use Logrus with the package-level logger and adding fields to log entries. ```go package main import ( log "github.com/sirupsen/logrus" ) func main() { log.WithFields(log.Fields{ "animal": "walrus", }).Info("A walrus appears") } ``` -------------------------------- ### Install JSON-Patch v4 Source: https://github.com/kubevirt/hyperconverged-cluster-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 ``` -------------------------------- ### Drop Elements from Start of Slice in Go Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/vendor/github.com/samber/lo/README.md Drops a specified number of elements from the beginning of a slice. ```go l := lo.Drop([]int{0, 1, 2, 3, 4, 5}, 2) // []int{2, 3, 4, 5} ``` -------------------------------- ### Example Merge Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/vendor/dario.cat/mergo/README.md Demonstrates a simple merge operation where the destination struct is updated with values from the source struct. ```go package main import ( "fmt" "dario.cat/mergo" ) type Foo struct { A string B int64 } func main() { src := Foo{ A: "one", B: 2, } dest := Foo{ A: "two", } mergo.Merge(&dest, src) fmt.Println(dest) // Will print // {two 2} } ``` -------------------------------- ### Automated HCO Deployment using Image Registry with KVM Emulation Source: https://github.com/kubevirt/hyperconverged-cluster-operator/blob/main/deploy/kustomize/README.md Automate HCO deployment using the deploy script with MARKETPLACE_MODE set to false, KVM_EMULATION to true, and CONTENT_ONLY to false. ```bash $ MARKETPLACE_MODE=false \ KVM_EMULATION=true \ CONTENT_ONLY=false \ ./deploy/kustomize/deploy_kustomize.sh ```