### Define a RESTful Web Service with Routes in Go Source: https://github.com/kubevirt/ipam-extensions/blob/main/vendor/github.com/emicklei/go-restful/v3/README.md This Go code example illustrates the basic setup of a WebService using go-restful. It defines a path, content types for consumption and production, and a GET route with path parameters, documentation, and a specified response type. It also shows how to extract path parameters within a handler function. ```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") // ... } ``` -------------------------------- ### Basic fsnotify Watcher Example in Go Source: https://github.com/kubevirt/ipam-extensions/blob/main/vendor/github.com/fsnotify/fsnotify/README.md This Go code demonstrates how to create a new fsnotify watcher, start listening for file system events (write, create, remove, etc.) and errors in a separate goroutine, and add a directory to watch. It requires the fsnotify library and Go 1.17 or newer. ```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{})) } ``` -------------------------------- ### Build Installer for ipam-extensions with Make Source: https://github.com/kubevirt/ipam-extensions/blob/main/README.md Generates an installer YAML file (install.yaml) in the 'dist' directory. This file contains all necessary Kubernetes resources for deploying the ipam-project, excluding its dependencies like cert-manager. ```sh make build-installer IMG=/ipam-controller: ``` -------------------------------- ### Setup KubeVirt IPAM Controller Manager and Webhook Server in Go Source: https://context7.com/kubevirt/ipam-extensions/llms.txt This Go code demonstrates the setup of the KubeVirt IPAM Controller manager. It initializes the manager, registers controllers for VirtualMachine and VirtualMachineInstance resources, and sets up a mutating webhook for pod admission. Dependencies include controller-runtime, KubeVirt API, Network Attachment Definition client, and IPAMClaims CRD client. ```go package main import ( "flag" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/healthz" "sigs.k8s.io/controller-runtime/pkg/webhook" virtv1 "kubevirt.io/api/core/v1" nadv1 "github.com/k8snetworkplumbingwg/network-attachment-definition-client/pkg/apis/k8s.cni.cncf.io/v1" ipamclaimsapi "github.com/k8snetworkplumbingwg/ipamclaims/pkg/crd/ipamclaims/v1alpha1" "github.com/kubevirt/ipam-extensions/pkg/vmnetworkscontroller" "github.com/kubevirt/ipam-extensions/pkg/vminetworkscontroller" "github.com/kubevirt/ipam-extensions/pkg/ipamclaimswebhook" ) func main() { // Parse command-line flags var enableLeaderElection bool var probeAddr string var certDir string var defaultNetworkNadNamespace string flag.StringVar(&probeAddr, "health-probe-bind-address", ":8081", "The address the probe endpoint binds to.") flag.BoolVar(&enableLeaderElection, "leader-elect", false, "Enable leader election for controller manager.") flag.StringVar(&certDir, "certificates-dir", "", "The directory where TLS certificates are stored.") flag.StringVar(&defaultNetworkNadNamespace, "default-network-nad-namespace", "ovn-kubernetes", "The namespace where default network NAD is located.") flag.Parse() // Create controller manager with webhook server webhookServer := webhook.NewServer(webhook.Options{ Port: 9443, CertDir: certDir, }) mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{ Scheme: scheme, HealthProbeBindAddress: probeAddr, LeaderElection: enableLeaderElection, LeaderElectionID: "71d89df3.kubevirt.io", WebhookServer: webhookServer, }) if err != nil { setupLog.Error(err, "unable to start manager") os.Exit(1) } // Register VirtualMachine controller for cleanup if err = vmnetworkscontroller.NewVMReconciler(mgr).Setup(); err != nil { setupLog.Error(err, "unable to create VM controller") os.Exit(1) } // Register VirtualMachineInstance controller for IPAM claim creation if err = vminetworkscontroller.NewVMIReconciler(mgr).Setup(); err != nil { setupLog.Error(err, "unable to create VMI controller") os.Exit(1) } // Register pod mutation webhook mgr.GetWebhookServer().Register( "/mutate-v1-pod", &webhook.Admission{ Handler: ipamclaimswebhook.NewIPAMClaimsValet( mgr, ipamclaimswebhook.WithDefaultNetNADNamespace(defaultNetworkNadNamespace), ), }, ) // Add health checks if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil { setupLog.Error(err, "unable to set up health check") os.Exit(1) } // Start manager setupLog.Info("starting manager") if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil { setupLog.Error(err, "problem running manager") os.Exit(1) } } ``` -------------------------------- ### Install ipam-extensions using kubectl Source: https://github.com/kubevirt/ipam-extensions/blob/main/README.md Applies the generated installer YAML file to the Kubernetes cluster to deploy the ipam-extensions project. This command assumes the install.yaml has been built or is accessible via a URL. ```sh kubectl apply -f https://raw.githubusercontent.com/kubevirt/ipam-extensions/main/dist/install.yaml ``` -------------------------------- ### fsnotify Test Script Syntax Example Source: https://github.com/kubevirt/ipam-extensions/blob/main/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md This example demonstrates the syntax for writing new test cases in the testdata directory. It shows a script section followed by the expected output, mimicking shell commands and their results. ```bash # Create a new empty file with some data. watch / echo data >/file Output: create /file write /file ``` -------------------------------- ### Initialize Procfs and Get CPU Stats (Go) Source: https://github.com/kubevirt/ipam-extensions/blob/main/vendor/github.com/prometheus/procfs/README.md Initializes the proc filesystem mount point and retrieves CPU statistics. This function requires the path to the proc filesystem as input. ```go fs, err := procfs.NewFS("/proc") stats, err := fs.Stat() ``` -------------------------------- ### Multi-Network VM Deployment Example with YAML Source: https://context7.com/kubevirt/ipam-extensions/llms.txt This YAML defines a complete end-to-end example for creating a Virtual Machine (VM) with multiple networks and persistent IP addresses. It includes definitions for NetworkAttachmentDefinitions, the VirtualMachine resource itself, and the expected IPAMClaims and pod annotations that are automatically created or mutated by the system. This demonstrates the integration of IPAM with KubeVirt for advanced networking configurations. ```yaml # 1. Create NetworkAttachmentDefinitions --- apiVersion: k8s.cni.cncf.io/v1 kind: NetworkAttachmentDefinition metadata: name: primary-udn namespace: default spec: config: | { "name": "primary-network", "role": "primary", "allowPersistentIPs": true, "subnets": "10.0.0.0/24,2001:db8::/64", "cniVersion": "0.4.0", "type": "ovn-k8s-cni-overlay" } --- apiVersion: k8s.cni.cncf.io/v1 kind: NetworkAttachmentDefinition metadata: name: secondary-net namespace: default spec: config: | { "name": "data-network", "allowPersistentIPs": true, "subnets": "192.168.1.0/24", "cniVersion": "0.3.1", "type": "ovn-k8s-cni-overlay" } # 2. Create VirtualMachine with IP requests --- apiVersion: kubevirt.io/v1 kind: VirtualMachine metadata: name: multi-net-vm namespace: default annotations: network.kubevirt.io/addresses: | { "eth0": ["10.0.0.100", "2001:db8::100"], "eth1": ["192.168.1.50"] } spec: runStrategy: Always template: metadata: labels: kubevirt.io/vm: multi-net-vm spec: domain: devices: interfaces: - name: eth0 bridge: {} macAddress: "02:00:00:00:00:01" - name: eth1 bridge: {} macAddress: "02:00:00:00:00:02" resources: requests: memory: 2Gi cpu: "2" networks: - name: eth0 pod: {} - name: eth1 multus: networkName: secondary-net # 3. Controller automatically creates IPAMClaims # Expected IPAMClaims (created automatically): --- apiVersion: k8s.cni.cncf.io/v1alpha1 kind: IPAMClaim metadata: name: multi-net-vm.eth0 namespace: default labels: kubevirt.io/vm: multi-net-vm finalizers: - kubevirt.io/persistent-ipam ownerReferences: - apiVersion: kubevirt.io/v1 kind: VirtualMachine name: multi-net-vm uid: spec: network: primary-network --- apiVersion: k8s.cni.cncf.io/v1alpha1 kind: IPAMClaim metadata: name: multi-net-vm.eth1 namespace: default labels: kubevirt.io/vm: multi-net-vm finalizers: - kubevirt.io/persistent-ipam ownerReferences: - apiVersion: kubevirt.io/v1 kind: VirtualMachine name: multi-net-vm uid: spec: network: data-network # 4. Webhook mutates launcher pod (automatic) # Expected pod annotations after mutation: # k8s.v1.cni.cncf.io/networks: '[{"name":"data-network","namespace":"default","ipamClaimReference":"multi-net-vm.eth1"}]' # v1.multus-cni.io/default-network: '{"name":"default","namespace":"default","interface":"eth0","mac":"02:00:00:00:00:01","ipamClaimReference":"multi-net-vm.eth0","ips":["10.0.0.100/24","2001:db8::100/64"]}' # k8s.ovn.org/primary-udn-ipamclaim: multi-net-vm.eth0 ``` -------------------------------- ### Go: Create Root Logger with Implementation Source: https://github.com/kubevirt/ipam-extensions/blob/main/vendor/github.com/go-logr/logr/README.md This snippet demonstrates how to create the root logger in a Go application using a specific logging implementation. It shows the typical setup in the main function before other application logic executes. This is crucial for initializing the logging framework. ```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 ... } ``` -------------------------------- ### Go YAML Encoding and Decoding Example Source: https://github.com/kubevirt/ipam-extensions/blob/main/vendor/gopkg.in/yaml.v3/README.md Demonstrates how to use the `gopkg.in/yaml.v3` package to unmarshal YAML data into a Go struct and a map, and then marshal them back into YAML format. This example highlights basic YAML processing in Go. ```Go package main import ( "fmt" "log" "gopkg.in/yaml.v3" ) var data = ` a: Easy! b: c: 2 d: [3, 4] ` // Note: struct fields must be public in order for unmarshal to // correctly populate the data. type T struct { A string B struct { RenamedC int `yaml:"c"` D []int `yaml:",flow"` } } func main() { t := T{} err := yaml.Unmarshal([]byte(data), &t) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("--- t:\n%v\n\n", t) d, err := yaml.Marshal(&t) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("--- t dump:\n%s\n\n", string(d)) m := make(map[interface{}]interface{}) err = yaml.Unmarshal([]byte(data), &m) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("--- m:\n%v\n\n", m) d, err = yaml.Marshal(&m) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("--- m dump:\n%s\n\n", string(d)) } ``` -------------------------------- ### Go: Example using TagSet and TagOptions for CBOR decoding/encoding Source: https://github.com/kubevirt/ipam-extensions/blob/main/vendor/github.com/fxamacker/cbor/v2/README.md Provides a practical example of creating a TagSet, registering custom tags with specific options, and using them to decode and encode CBOR data with a custom struct. Shows both decoding and encoding with immutable tags. ```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 := cbor.Marshal(v); err != nil { return err } ``` -------------------------------- ### Install json-iterator/go Source: https://github.com/kubevirt/ipam-extensions/blob/main/vendor/github.com/json-iterator/go/README.md Provides the command to install the json-iterator/go library using the Go toolchain. This is the standard method for adding external Go packages to a project. ```bash go get github.com/json-iterator/go ``` -------------------------------- ### Apply JSON Patches via CLI Source: https://github.com/kubevirt/ipam-extensions/blob/main/vendor/gopkg.in/evanphx/json-patch.v4/README.md Demonstrates the usage of the `json-patch` command-line tool to apply multiple JSON patch files to a JSON document provided via stdin. The tool requires installation via `go install github.com/evanphx/json-patch/cmd/json-patch`. The output is the modified JSON document. ```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"} ``` -------------------------------- ### Initialize Block Device Filesystem and Get Disk Stats (Go) Source: https://github.com/kubevirt/ipam-extensions/blob/main/vendor/github.com/prometheus/procfs/README.md Initializes a filesystem object that can access both proc and sys filesystems, then retrieves statistics for block devices (disk drives). This requires paths to both /proc and /sys. ```go fs, err := blockdevice.NewFS("/proc", "/sys") stats, err := fs.ProcDiskstats() ``` -------------------------------- ### Setup Git Repository for zap Contributions Source: https://github.com/kubevirt/ipam-extensions/blob/main/vendor/go.uber.org/zap/CONTRIBUTING.md This bash script demonstrates how to fork the zap repository, clone it locally, add the upstream remote, and fetch the latest changes. It's a standard procedure for contributing to open-source projects. ```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 ``` -------------------------------- ### Coexist klog v1 and v2 in Go Source: https://github.com/kubevirt/ipam-extensions/blob/main/vendor/k8s.io/klog/v2/README.md Provides an example of how to manage and use both klog/v1 and klog/v2 within the same Go application. This is essential during migration phases or when dependencies require different versions. ```go import ( "k8s.io/klog/v1" "k8s.io/klog/v2" ) func main() { // Initialize v2 flags klog.InitFlags(nil) // Use v1 logging klogv1.Info("Message from klog/v1") // Use v2 logging klog.Info("Message from klog/v2") } ``` -------------------------------- ### Create GitHub Release - Bash Source: https://github.com/kubevirt/ipam-extensions/blob/main/vendor/github.com/onsi/ginkgo/v2/RELEASING.md This bash command creates a new GitHub release using the GitHub CLI. It requires the 'gh' tool to be installed and authenticated. The release is tagged with the specified version (e.g., 'vM.m.p') and fetched from the origin master branch. This action requires the latest changes to be committed and pushed prior to execution. ```bash git commit -m "vM.m.p" git push gh release create "vM.m.p" git fetch --tags origin master ``` -------------------------------- ### Running xxhash Benchmarks with benchstat Source: https://github.com/kubevirt/ipam-extensions/blob/main/vendor/github.com/cespare/xxhash/v2/README.md Demonstrates how to use the 'benchstat' tool to compare the performance of pure Go and assembly implementations of the Sum64 function. Requires Go test output and the benchstat utility. ```Shell # For pure Go implementation: benchstat <(go test -tags purego -benchtime 500ms -count 15 -bench 'Sum64$') # For assembly implementation: benchstat <(go test -benchtime 500ms -count 15 -bench 'Sum64$') ``` -------------------------------- ### Go: Marshal and Unmarshal YAML with Structs Source: https://github.com/kubevirt/ipam-extensions/blob/main/vendor/sigs.k8s.io/yaml/README.md Demonstrates how to marshal a Go struct into YAML format and unmarshal YAML data back into a Go struct. It utilizes JSON struct tags for field mapping and relies on the sigs.k8s.io/yaml package. Ensure the package is installed via `go get sigs.k8s.io/yaml`. ```go package main import ( "fmt" "sigs.k8s.io/yaml" ) type Person struct { Name string `json:"name"` // Affects YAML field names too. Age int `json:"age"` } func main() { // Marshal a Person struct to YAML. p := Person{"John", 30} y, err := yaml.Marshal(p) if err != nil { fmt.Printf("err: %v\n", err) return } fmt.Println(string(y)) /* Output: age: 30 name: John */ // Unmarshal the YAML back into a Person struct. var p2 Person err = yaml.Unmarshal(y, &p2) if err != nil { fmt.Printf("err: %v\n", err) return } fmt.Println(p2) /* Output: {John 30} */ } ``` -------------------------------- ### Go: Convert JSON to YAML and YAML to JSON Source: https://github.com/kubevirt/ipam-extensions/blob/main/vendor/sigs.k8s.io/yaml/README.md Provides functions to directly convert JSON byte slices to YAML byte slices and vice versa using the sigs.k8s.io/yaml package. This is useful for data transformation tasks where direct format conversion is needed. Ensure the package is installed via `go get sigs.k8s.io/yaml`. ```go package main import ( "fmt" "sigs.k8s.io/yaml" ) func main() { j := []byte(`{"name": "John", "age": 30}`) y, err := yaml.JSONToYAML(j) if err != nil { fmt.Printf("err: %v\n", err) return } fmt.Println(string(y)) /* Output: age: 30 name: John */ j2, err := yaml.YAMLToJSON(y) if err != nil { fmt.Printf("err: %v\n", err) return } fmt.Println(string(j2)) /* Output: {"age":30,"name":"John"} */ } ``` -------------------------------- ### Basic Info Logging with glog Source: https://github.com/kubevirt/ipam-extensions/blob/main/vendor/k8s.io/klog/v2/README.md Demonstrates basic usage of the glog.Info function for standard log messages. No specific dependencies are required beyond the glog package itself. It takes a string message as input. ```go glog.Info("Prepare to repel boarders") ``` -------------------------------- ### Using Slim-Sprig Functions in Templates Source: https://github.com/kubevirt/ipam-extensions/blob/main/vendor/github.com/go-task/slim-sprig/v3/README.md This example shows how to call Slim-Sprig functions within a Go template. Functions are typically lowercase and chained using the pipe operator. This specific example converts a string to uppercase and then repeats it. ```go-template {{ "hello!" | upper | repeat 5 }} ``` -------------------------------- ### Go: Basic Structured Logging with controller-runtime Source: https://github.com/kubevirt/ipam-extensions/blob/main/vendor/sigs.k8s.io/controller-runtime/TMP-LOGGING.md Demonstrates how to log a message with key-value pairs using the controller-runtime logger, contrasting it with the standard Go log package. This approach structures logs for easier searching and correlation. ```go log.Printf("starting reconciliation for pod %s/%s", podNamespace, podName) logger.Info("starting reconciliation", "pod", req.NamespacedName) ``` -------------------------------- ### Build and Push Docker Image with Make Source: https://github.com/kubevirt/ipam-extensions/blob/main/README.md This command builds the Docker image for the ipam-controller and pushes it to a specified registry. It requires Docker and a configured registry. The IMG variable must be set to your registry path and tag. ```sh make docker-build docker-push IMG=/ipam-controller: ``` -------------------------------- ### Run Tests with Go - KubeVirt IPAM Extensions Source: https://github.com/kubevirt/ipam-extensions/blob/main/vendor/gopkg.in/evanphx/json-patch.v4/README.md This command executes all tests within the project and reports code coverage. It is essential for contributors to run this before submitting pull requests to ensure code quality and that new functionality is adequately tested. ```bash go test -cover "./..." ``` -------------------------------- ### Add or Update Dependencies with Go Get Source: https://github.com/kubevirt/ipam-extensions/blob/main/vendor/github.com/prometheus/procfs/CONTRIBUTING.md Demonstrates how to manage external package dependencies using Go modules. This involves specifying the module path and optionally a version tag. ```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 ``` -------------------------------- ### Coexist glog and klog in Go Source: https://github.com/kubevirt/ipam-extensions/blob/main/vendor/k8s.io/klog/v2/README.md Illustrates how to run klog alongside the original glog library. It covers initializing and synchronizing flags from the global `flag.CommandLine` FlagSet and directing logs to stderr. ```go import ( "flag" "k8s.io/klog/v2" // Assuming glog is imported as "github.com/golang/glog" ) func main() { // Initialize klog flags klog.InitFlags(nil) // Set alsologtostderr to true for combined output flag.Set("alsologtostderr", "true") // You might need to initialize glog flags separately if needed // glog.InitFlags(nil) // ... rest of your application logic klog.Info("klog message") // glog.Info("glog message") } ``` -------------------------------- ### Unconditional Trace Logging and Introspection in Go Source: https://github.com/kubevirt/ipam-extensions/blob/main/vendor/k8s.io/utils/trace/README.md Provides examples of unconditionally logging a trace and retrieving its total execution time. This is useful for debugging and understanding the complete lifecycle of an operation trace. ```go opTrace.TotalTime() // Duration since the Trace was created opTrace.Log() // unconditionally log the trace ``` -------------------------------- ### Fuzzing Maps with gofuzz Source: https://github.com/kubevirt/ipam-extensions/blob/main/vendor/github.com/google/gofuzz/README.md Illustrates how to use gofuzz to populate a map. This example customizes the fuzzing behavior to ensure the map has exactly one element by setting NilChance to 0 and NumElements to 1. ```go f := fuzz.New().NilChance(0).NumElements(1, 1) var myMap map[ComplexKeyType]string f.Fuzz(&myMap) // myMap will have exactly one element. ``` -------------------------------- ### Split Operation Trace into Steps in Go Source: https://github.com/kubevirt/ipam-extensions/blob/main/vendor/k8s.io/utils/trace/README.md Illustrates how to break down a single operation trace into distinct steps, logging details for each step. This allows for finer-grained performance analysis within a larger operation. ```go func doSomething() { opTrace := trace.New("operation") defer opTrace.LogIfLong(100 * time.Millisecond) // do step 1 opTrace.Step("step1", Field{Key: "stepFieldKey1", Value: "stepFieldValue1"}) // do step 2 opTrace.Step("step2") } ``` -------------------------------- ### fsnotify Test Script - Skip Conditions Source: https://github.com/kubevirt/ipam-extensions/blob/main/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md Illustrates the `require` and `skip` commands in fsnotify test scripts, used to conditionally skip tests based on platform features or other reasons. 'always', 'symlink', 'mkfifo', and 'mknod' are examples of reasons. ```bash require reason skip reason # Possible reasons: # always # symlink # mkfifo # mknod ``` -------------------------------- ### Creating Custom CBOR Encoding Modes in Go Source: https://github.com/kubevirt/ipam-extensions/blob/main/vendor/github.com/fxamacker/cbor/v2/README.md Illustrates how to create custom CBOR encoding modes by starting with a preset, modifying settings like time format, and then creating an immutable encoding mode. This mode can then be reused safely for concurrent encoding operations. ```go // Create encoding mode. opts := cbor.CoreDetEncOptions() // use preset options as a starting point opts.Time = cbor.TimeUnix // change any settings if needed em, err := opts.EncMode() // create an immutable encoding mode // Reuse the encoding mode. It is safe for concurrent use. // API matches encoding/json. b, err := em.Marshal(v) // encode v to []byte b encoder := em.NewEncoder(w) // create encoder with io.Writer w err := encoder.Encode(v) // encode v to io.Writer w ``` -------------------------------- ### Create and Log Operation Trace in Go Source: https://github.com/kubevirt/ipam-extensions/blob/main/vendor/k8s.io/utils/trace/README.md Demonstrates how to create a new trace for an operation, add initial fields, and log it if its execution time exceeds a specified duration. This is useful for performance monitoring and identifying slow operations. ```go func doSomething() { opTrace := trace.New("operation", Field{Key: "fieldKey1", Value: "fieldValue1"}) defer opTrace.LogIfLong(100 * time.Millisecond) // do something } ``` -------------------------------- ### Get Type by Name using reflect2.TypeByName Source: https://github.com/kubevirt/ipam-extensions/blob/main/vendor/github.com/modern-go/reflect2/README.md Retrieves a type by its fully qualified name, similar to Java's `Class.forName`. Note that types not used in the program might be eliminated by the compiler, preventing runtime retrieval. ```go // given package is github.com/your/awesome-package type MyStruct struct { // ... } // will return the type reflect2.TypeByName("awesome-package.MyStruct") // however, if the type has not been used // it will be eliminated by compiler, so we can not get it in runtime ``` -------------------------------- ### Check Version Against Constraints (Go) Source: https://github.com/kubevirt/ipam-extensions/blob/main/vendor/github.com/Masterminds/semver/v3/README.md This Go code snippet demonstrates how to create a version constraint and check if a given version satisfies it. It requires the `semver` package. The output is a boolean indicating whether the version meets the constraint. ```Go c, err := semver.NewConstraint(">= 1.2.3") if err != nil { // Handle constraint not being parsable. } v, err := semver.NewVersion("1.3") if err != nil { // Handle version not being parsable. } // Check if the version meets the constraints. The a variable will be true. a := c.Check(v) ``` -------------------------------- ### xxhash Benchmarking Commands Source: https://github.com/kubevirt/ipam-extensions/blob/main/vendor/github.com/klauspost/compress/zstd/internal/xxhash/README.md Commands to benchmark the pure Go and assembly implementations of the Sum64 function using benchstat. These commands help compare performance under different build tags and conditions. ```bash benchstat <(go test -tags purego -benchtime 500ms -count 15 -bench 'Sum64$') benchstat <(go test -benchtime 500ms -count 15 -bench 'Sum64$') ``` -------------------------------- ### Go: Convert float32 to float16 and vice versa Source: https://github.com/kubevirt/ipam-extensions/blob/main/vendor/github.com/x448/float16/README.md Demonstrates converting between float32 and float16 using the float16 package. It includes examples for direct conversion and checking precision before conversion. The float16 package handles IEEE 754 half-precision floating-point conversions. ```Go package main import ( "fmt" "math" "github.com/x448/float16" ) func main() { // Convert float32 to float16 pi := float32(math.Pi) pi16 := float16.Fromfloat32(pi) // Convert float16 to float32 pi32 := pi16.Float32() fmt.Printf("Original float32: %f\n", pi) fmt.Printf("Converted float16: %f\n", pi16) fmt.Printf("Converted back to float32: %f\n", pi32) // 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 { pi16Exact := float16.Fromfloat32(pi) fmt.Printf("Exact conversion to float16: %f\n", pi16Exact) } else { fmt.Println("Precision loss during conversion.") } } ``` -------------------------------- ### Integrating gofuzz with go-fuzz Source: https://github.com/kubevirt/ipam-extensions/blob/main/vendor/github.com/google/gofuzz/README.md Provides an example of how to use gofuzz to convert byte slices from go-fuzz into appropriate inputs for a Go function. This specific snippet shows how to fuzz an integer argument for a function named MyFunc. ```go // +build gofuzz package mypackage import fuzz "github.com/google/gofuzz" func Fuzz(data []byte) int { var i int fuzz.NewFromGoFuzz(data).Fuzz(&i) MyFunc(i) return 0 } ```