### Install Flect Source: https://github.com/squat/kilo/blob/main/vendor/github.com/gobuffalo/flect/README.md Install the flect package using go get. ```console go get github.com/gobuffalo/flect ``` -------------------------------- ### Install go-isatty Package Source: https://github.com/squat/kilo/blob/main/vendor/github.com/mattn/go-isatty/README.md Install the go-isatty package using the go get command. This command fetches and installs the package and its dependencies. ```bash go get github.com/mattn/go-isatty ``` -------------------------------- ### Install wgctrl Package Source: https://github.com/squat/kilo/blob/main/vendor/golang.zx2c4.com/wireguard/wgctrl/README.md Install the wgctrl package using go get. ```text go get golang.zx2c4.com/wireguard/wgctrl ``` -------------------------------- ### Install Go Color Package Source: https://github.com/squat/kilo/blob/main/vendor/github.com/fatih/color/README.md Install the color package using go get. ```bash go get github.com/fatih/color ``` -------------------------------- ### Install Cobra Library Source: https://github.com/squat/kilo/blob/main/vendor/github.com/spf13/cobra/README.md Use 'go get' to install the latest version of the Cobra library. ```go go get -u github.com/spf13/cobra@latest ``` -------------------------------- ### Install json-iterator/go Source: https://github.com/squat/kilo/blob/main/vendor/github.com/json-iterator/go/README.md Install the json-iterator/go library using the go get command. ```go go get github.com/json-iterator/go ``` -------------------------------- ### Install and Import YAML Package Source: https://github.com/squat/kilo/blob/main/vendor/sigs.k8s.io/yaml/README.md Install the package using go get and import it in your Go programs. ```bash $ go get sigs.k8s.io/yaml ``` ```go import "sigs.k8s.io/yaml" ``` -------------------------------- ### Install go-colorable Package Source: https://github.com/squat/kilo/blob/main/vendor/github.com/mattn/go-colorable/README.md Standard Go installation command for the go-colorable package. ```bash $ go get github.com/mattn/go-colorable ``` -------------------------------- ### Install uuid Package Source: https://github.com/squat/kilo/blob/main/vendor/github.com/google/uuid/README.md Installs the uuid package using the go get command. ```sh go get github.com/google/uuid ``` -------------------------------- ### Start Local Development Server Source: https://github.com/squat/kilo/blob/main/website/README.md Starts a local development server for live preview. Changes are reflected without restarting. ```bash yarn start ``` -------------------------------- ### Install TOML Parser Source: https://github.com/squat/kilo/blob/main/vendor/github.com/BurntSushi/toml/README.md Install the TOML parser library for Go using the go get command. Requires Go 1.13 or newer. ```bash $ go get github.com/BurntSushi/toml ``` -------------------------------- ### Start Website Server Source: https://github.com/squat/kilo/blob/main/docs/building_website.md Start the local development server for the website. This command should automatically open the site in your browser. ```shell yarn --cwd website start ``` -------------------------------- ### Go Example: Create and Interact with a New Network Namespace Source: https://github.com/squat/kilo/blob/main/vendor/github.com/vishvananda/netns/README.md This example demonstrates how to create a new network namespace, perform operations within it (like listing interfaces), and then switch back to the original namespace. It's crucial to lock the OS thread and defer unlocking to ensure namespace stability. ```go package main import ( "fmt" "net" "runtime" "github.com/vishvananda/netns" ) func main() { // Lock the OS Thread so we don't accidentally switch namespaces runtime.LockOSThread() defer runtime.UnlockOSThread() // Save the current network namespace origns, _ := netns.Get() defer origns.Close() // Create a new network namespace newns, _ := netns.New() defer newns.Close() // Do something with the network namespace ifaces, _ := net.Interfaces() fmt.Printf("Interfaces: %v\n", ifaces) // Switch back to the original namespace netns.Set(origns) } ``` -------------------------------- ### Install kgctl using Go Toolchain Source: https://github.com/squat/kilo/blob/main/docs/kgctl.md Installs the latest version of the kgctl binary using the Go toolchain. Ensure the Go toolchain is installed. ```shell go install github.com/squat/kilo/cmd/kgctl@latest ``` -------------------------------- ### Retrieve Network Device Statistics and Peer Index Source: https://github.com/squat/kilo/blob/main/vendor/github.com/safchain/ethtool/README.md This example demonstrates how to initialize the ethtool handler, retrieve transmit statistics (tx_bytes) for 'eth0', and get the peer interface index for 'veth0'. Ensure the network interfaces exist and the program has necessary permissions. ```go package main import ( "fmt" "github.com/safchain/ethtool" ) func main() { ethHandle, err := ethtool.NewEthtool() if err != nil { panic(err.Error()) } defer ethHandle.Close() // Retrieve tx from eth0 stats, err := ethHandle.Stats("eth0") if err != nil { panic(err.Error()) } fmt.Printf("TX: %d\n", stats["tx_bytes"]) // Retrieve peer index of a veth interface stats, err = ethHandle.Stats("veth0") if err != nil { panic(err.Error()) } fmt.Printf("Peer Index: %d\n", stats["peer_ifindex"]) } ``` -------------------------------- ### Install Dependencies Source: https://github.com/squat/kilo/blob/main/website/README.md Installs project dependencies using Yarn. This is the first step before running any other commands. ```bash yarn ``` -------------------------------- ### Install kgctl using Mise Source: https://github.com/squat/kilo/blob/main/docs/kgctl.md Installs kgctl using the mise version manager. Updates will be installed automatically with 'mise up'. ```bash mise use -g github:squat/kilo@latest ``` -------------------------------- ### Install kgctl using Arkade CLI Source: https://github.com/squat/kilo/blob/main/docs/kgctl.md Installs the kgctl binary on any OS and architecture using the arkade CLI. ```shell arkade get kgctl ``` -------------------------------- ### Coexisting with glog Source: https://github.com/squat/kilo/blob/main/vendor/k8s.io/klog/v2/README.md Example demonstrating how to use klog and glog simultaneously. It shows flag synchronization and redirecting output to stderr. ```go package main import ( "flag" "github.com/golang/glog" "k8s.io/klog/v2" ) func main() { // Initialize flags for both klog and glog from the command line. klog.InitFlags(nil) glog.InitFlags() // Set alsologtostderr to true to combine output to stderr. flag.Set("alsologtostderr", "true") klog.Info("This is a klog message.") glog.Info("This is a glog message.") klog.Flush() glog.Flush() } ``` -------------------------------- ### Install YAML Package for Go Source: https://github.com/squat/kilo/blob/main/vendor/go.yaml.in/yaml/v3/README.md Run this command to install the yaml v3 package for your Go projects. ```bash go get go.yaml.in/yaml/v3 ``` -------------------------------- ### Install Latest JSON-Patch v5 Source: https://github.com/squat/kilo/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 ``` -------------------------------- ### Create Root Logger with Implementation Source: https://github.com/squat/kilo/blob/main/vendor/github.com/go-logr/logr/README.md Example of creating the root logger in an application's main function, choosing a specific logging implementation (e.g., 'logimpl') and passing 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/squat/kilo/blob/main/vendor/github.com/fxamacker/cbor/v2/README.md Illustrates creating a TagSet, adding custom tag options and types, and then using this TagSet to create decoding and encoding modes for handling specific CBOR 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 := em.Marshal(v); err != nil { return err } ``` -------------------------------- ### Install embedmd with Go Source: https://github.com/squat/kilo/blob/main/vendor/github.com/campoy/embedmd/README.md Install the embedmd tool using the Go package manager. This command downloads, compiles, and installs the embedmd binary. ```bash go get github.com/campoy/embedmd ``` -------------------------------- ### Install Kilo on bootkube Source: https://github.com/squat/kilo/blob/main/README.md Apply the necessary CRDs and Kilo DaemonSet for bootkube installations. ```shell kubectl apply -f https://raw.githubusercontent.com/squat/kilo/main/manifests/crds.yaml kubectl apply -f https://raw.githubusercontent.com/squat/kilo/main/manifests/kilo-bootkube.yaml ``` -------------------------------- ### Install Cobra CLI Generator Source: https://github.com/squat/kilo/blob/main/vendor/github.com/spf13/cobra/README.md Install the cobra-cli command line program to generate Cobra application scaffolding. ```go go install github.com/spf13/cobra-cli@latest ``` -------------------------------- ### Install Kilo on kubeadm Source: https://github.com/squat/kilo/blob/main/README.md Apply the necessary CRDs and Kilo DaemonSet for kubeadm installations. ```shell kubectl apply -f https://raw.githubusercontent.com/squat/kilo/main/manifests/crds.yaml kubectl apply -f https://raw.githubusercontent.com/squat/kilo/main/manifests/kilo-kubeadm.yaml ``` -------------------------------- ### Install kgctl using AUR Helper Source: https://github.com/squat/kilo/blob/main/docs/kgctl.md Installs the kgctl binary package from the Arch User Repository using an AUR helper like paru or yay. ```shell paru -S kgctl-bin ``` -------------------------------- ### Install Specific kgctl Version using Go Toolchain Source: https://github.com/squat/kilo/blob/main/docs/kgctl.md Installs a specific version of the kgctl binary using the Go toolchain. Specify the desired Git tag or hash. ```shell go install github.com/squat/kilo/cmd/kgctl@0.2.0 ``` -------------------------------- ### Basic WebService Definition and Route Source: https://github.com/squat/kilo/blob/main/vendor/github.com/emicklei/go-restful/v3/README.md Defines a WebService with a path, consumes/produces media types, and a GET route for retrieving a user. The route includes documentation and path parameter definition. ```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") ... } ``` -------------------------------- ### Command Line Flag Syntax Examples Source: https://github.com/squat/kilo/blob/main/vendor/github.com/spf13/pflag/README.md Illustrates different ways to specify flags on the command line, including long form, shorthand, and value assignment. ```bash --flag // boolean flags, or flags with no option default values --flag x // only on flags without a default value --flag=x ``` ```bash // boolean or flags where the 'no option default value' is set -f -f=true -abc but -b true is INVALID // non-boolean and flags without a 'no option default value' -n 1234 -n=1234 -n1234 // mixed -abcs "hello" -absd="hello" -abcs1234 ``` -------------------------------- ### Go YAML Marshal and Unmarshal Example Source: https://github.com/squat/kilo/blob/main/vendor/go.yaml.in/yaml/v2/README.md Demonstrates how to unmarshal YAML data into a Go struct and a map, and then marshal them back into YAML. Ensure struct fields are public for correct unmarshalling. ```Go package main import ( "fmt" "log" "go.yaml.in/yaml/v2" ) var data = ` a: Easy! b: c: 2 d: [3, 4] ` // Note: struct fields must be public in order for unmarshal to // correctly populate the data. type T struct { A string B struct { RenamedC int `yaml:"c"` D []int `yaml:",flow"` } } func main() { t := T{} err := yaml.Unmarshal([]byte(data), &t) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("--- t:\n%v\n\n", t) d, err := yaml.Marshal(&t) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("--- t dump:\n%s\n\n", string(d)) m := make(map[interface{}]interface{}) err = yaml.Unmarshal([]byte(data), &m) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("--- m:\n%v\n\n", m) d, err = yaml.Marshal(&m) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("--- m dump:\n%s\n\n", string(d)) } ``` -------------------------------- ### Convert klog Infof to logr Info Source: https://github.com/squat/kilo/blob/main/vendor/github.com/go-logr/logr/README.md Example of converting a klog.Infof call with format specifiers to a logr.Info call with key-value pairs. Use this for general informational logging where details need to be structured. ```go logger.V(4).Info("got a retry-after response when requesting url", "attempt", retries, "after seconds", seconds, "url", url) ``` -------------------------------- ### CLI for Applying JSON Patches Source: https://github.com/squat/kilo/blob/main/vendor/gopkg.in/evanphx/json-patch.v4/README.md Demonstrates using the json-patch CLI tool to apply multiple patches to a JSON document provided via stdin. Requires installation of the CLI. ```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 ``` -------------------------------- ### Typical Application Logging with Logfmt Source: https://github.com/squat/kilo/blob/main/vendor/github.com/go-kit/kit/log/README.md Demonstrates basic structured logging using the logfmt format. It initializes a logger that writes to standard error. ```go w := log.NewSyncWriter(os.Stderr) logger := log.NewLogfmtLogger(w) logger.Log("question", "what is the meaning of life?", "answer", 42) // Output: // question="what is the meaning of life?" answer=42 ``` -------------------------------- ### Install Kilo on k3s Source: https://github.com/squat/kilo/blob/main/README.md Apply the necessary CRDs and Kilo DaemonSet for k3s installations. ```shell kubectl apply -f https://raw.githubusercontent.com/squat/kilo/main/manifests/crds.yaml kubectl apply -f https://raw.githubusercontent.com/squat/kilo/main/manifests/kilo-k3s.yaml ``` -------------------------------- ### Initialize Block Device Filesystem Source: https://github.com/squat/kilo/blob/main/vendor/github.com/prometheus/procfs/README.md Initializes both proc and sys filesystems to gather block device statistics. ```go fs, err := blockdevice.NewFS("/proc", "/sys") stats, err := fs.ProcDiskstats() ``` -------------------------------- ### Build All Container Images Source: https://github.com/squat/kilo/blob/main/docs/building_kilo.md Build the 'kg' container image for multiple architectures (arm, arm64, amd64) using Make. ```shell make all-container ``` -------------------------------- ### Install Kilo on Typhoon Source: https://github.com/squat/kilo/blob/main/README.md Apply the necessary CRDs and Kilo DaemonSet for Typhoon installations. ```shell kubectl apply -f https://raw.githubusercontent.com/squat/kilo/main/manifests/crds.yaml kubectl apply -f https://raw.githubusercontent.com/squat/kilo/main/manifests/kilo-typhoon.yaml ``` -------------------------------- ### Build Manifest and Push Images Source: https://github.com/squat/kilo/blob/main/docs/building_kilo.md Build a container manifest and push the container images to the configured registry. ```shell make manifest ``` -------------------------------- ### Initialize Procfs Filesystem Source: https://github.com/squat/kilo/blob/main/vendor/github.com/prometheus/procfs/README.md Initializes the proc filesystem mount point to gather CPU statistics. ```go fs, err := procfs.NewFS("/proc") stats, err := fs.Stat() ``` -------------------------------- ### Add a New Bridge and Add Interface to it Source: https://github.com/squat/kilo/blob/main/vendor/github.com/vishvananda/netlink/README.md Demonstrates creating a new bridge interface and assigning an existing interface (eth1) to it. Requires root privileges. ```go package main import ( "fmt" "github.com/vishvananda/netlink" ) func main() { la := netlink.NewLinkAttrs() la.Name = "foo" mybridge := &netlink.Bridge{LinkAttrs: la} err := netlink.LinkAdd(mybridge) if err != nil { fmt.Printf("could not add %s: %v\n", la.Name, err) } eth1, _ := netlink.LinkByName("eth1") netlink.LinkSetMaster(eth1, mybridge) } ``` -------------------------------- ### Install TOML Validator CLI Source: https://github.com/squat/kilo/blob/main/vendor/github.com/BurntSushi/toml/README.md Install the TOML validator command-line tool. This tool can be used to validate TOML files. ```bash $ go get github.com/BurntSushi/toml/cmd/tomlv $ tomlv some-toml-file.toml ``` -------------------------------- ### Contextual Loggers with Go Kit Source: https://github.com/squat/kilo/blob/main/vendor/github.com/go-kit/kit/log/README.md Shows how to create contextual loggers by wrapping an existing logger with additional key/value pairs. This is useful for adding common context like instance IDs or component names. ```go func main() { var logger log.Logger logger = log.NewLogfmtLogger(log.NewSyncWriter(os.Stderr)) logger = log.With(logger, "instance_id", 123) logger.Log("msg", "starting") NewWorker(log.With(logger, "component", "worker")).Run() NewSlacker(log.With(logger, "component", "slacker")).Run() } // Output: // instance_id=123 msg=starting // instance_id=123 component=worker msg=running // instance_id=123 component=slacker msg=running ``` -------------------------------- ### Nest Traces Source: https://github.com/squat/kilo/blob/main/vendor/k8s.io/utils/trace/README.md Demonstrates creating a root trace and then nesting a sub-trace within it, each with its own logging threshold. ```go func doSomething() { rootTrace := trace.New("rootOperation") defer rootTrace.LogIfLong(100 * time.Millisecond) func() { nestedTrace := rootTrace.Nest("nested", Field{Key: "nestedFieldKey1", Value: "nestedFieldValue1"}) defer nestedTrace.LogIfLong(50 * time.Millisecond) // do nested operation }() } ``` -------------------------------- ### Even Slice Length Validator Example Source: https://github.com/squat/kilo/blob/main/vendor/k8s.io/apimachinery/pkg/api/validate/README.md Example of a generic validator function that checks if a slice has an even number of items. It can be used with slices of any type. ```go // Even validates that a slice has an even number of items. func Even[T any](ctx context.Context, op operation.Operation, fldPath *field.Path, value, _ []T) field.ErrorList ``` -------------------------------- ### Install kube-router for Network Policy Support Source: https://github.com/squat/kilo/blob/main/docs/network-policies.md Installs kube-router to enable Kubernetes Network Policy functionality alongside Kilo. This is a prerequisite for applying network policies. ```shell kubectl apply -f https://raw.githubusercontent.com/squat/kilo/main/manifests/kube-router.yaml ``` -------------------------------- ### xxhash Benchmarking Commands Source: https://github.com/squat/kilo/blob/main/vendor/github.com/cespare/xxhash/v2/README.md Commands to run benchmarks for xxhash, comparing pure Go and assembly implementations. Use benchstat to analyze the results. ```bash benchstat <(go test -tags purego -benchtime 500ms -count 15 -bench 'Sum64$') benchstat <(go test -benchtime 500ms -count 15 -bench 'Sum64$') ``` -------------------------------- ### NonEmpty Validator Example Source: https://github.com/squat/kilo/blob/main/vendor/k8s.io/apimachinery/pkg/api/validate/README.md Example of a validator function that checks if a string value is not empty. It takes context, operation, field path, and the string value as input. ```go // NonEmpty validates that a string is not empty. func NonEmpty(ctx context.Context, op operation.Operation, fldPath *field.Path, value, _ *string) field.ErrorList ``` -------------------------------- ### Run Go Benchmarks Source: https://github.com/squat/kilo/blob/main/vendor/github.com/go-openapi/swag/BENCHMARK.md Command to execute benchmarks for the go-openapi/swag project. Use -bench XXX to specify benchmark functions and -run XXX to skip tests. ```bash go test -bench XXX -run XXX -benchtime 30s ``` -------------------------------- ### KeysMaxLen Validator Example Source: https://github.com/squat/kilo/blob/main/vendor/k8s.io/apimachinery/pkg/api/validate/README.md Example of a generic validator function that enforces a maximum length for all string keys in a map. It takes the map, maximum length, and other standard validator arguments. ```go // KeysMaxLen validates that all of the string keys in a map are under the // specified length. func KeysMaxLen[T any](ctx context.Context, op operation.Operation, fldPath *field.Path, value, _ map[string]T, maxLen int) field.ErrorList ``` -------------------------------- ### Embed content between two regular expressions Source: https://github.com/squat/kilo/blob/main/vendor/github.com/campoy/embedmd/README.md Embeds content starting from the first line matching the start regular expression and ending at the first line matching the end regular expression. This allows for embedding specific code blocks or sections. ```Markdown [embedmd]:# (pathOrURL language /start regexp/ /end regexp/) ``` -------------------------------- ### Split Trace into Steps Source: https://github.com/squat/kilo/blob/main/vendor/k8s.io/utils/trace/README.md Creates a trace and logs it if its duration exceeds a limit. It also demonstrates how to define and log individual steps within the trace. ```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") } ``` -------------------------------- ### Log to a Single File with klog Source: https://github.com/squat/kilo/blob/main/vendor/k8s.io/klog/v2/README.md Demonstrates how to configure klog to log to a single file using the 'log_file' flag, instead of a directory. ```go package main import ( "flag" "k8s.io/klog/v2" ) func main() { // Define and parse flags, including klog's logFile := flag.String("log_file", "", "Path to the log file.") flag.Parse() // Set the log file path for klog klog.SetLogFile(*logFile) // Now you can use klog for logging klog.Info("Logging to a single file") // Flush logs before exiting klog.Flush() } ``` -------------------------------- ### Example using Embedded JSON Tag for CBOR (tag 262) Source: https://github.com/squat/kilo/blob/main/vendor/github.com/fxamacker/cbor/v2/README.md Demonstrates encoding and decoding a tagged CBOR data item with tag number 262, where the tag content is a JSON object embedded as a CBOR byte string. This example defines custom MarshalCBOR and UnmarshalCBOR methods for a Go struct to handle this specific tag. ```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) } ``` -------------------------------- ### Install JSON-Patch v4 Source: https://github.com/squat/kilo/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 ``` -------------------------------- ### Build Website HTML Source: https://github.com/squat/kilo/blob/main/docs/building_website.md After generating markdown, use this command to build the website's HTML files. ```shell make website/build/index.html ``` -------------------------------- ### Trace Introspection and Unconditional Logging Source: https://github.com/squat/kilo/blob/main/vendor/k8s.io/utils/trace/README.md Shows how to get the total elapsed time of a trace and how to log the trace unconditionally. ```go opTrace.TotalTime() // Duration since the Trace was created opTrace.Log() // unconditionally log the trace ``` -------------------------------- ### Create and Log Trace Source: https://github.com/squat/kilo/blob/main/vendor/k8s.io/utils/trace/README.md Creates a new trace with initial fields and logs it if its duration exceeds a specified limit. ```go func doSomething() { opTrace := trace.New("operation", Field{Key: "fieldKey1", Value: "fieldValue1"}) defer opTrace.LogIfLong(100 * time.Millisecond) // do something } ``` -------------------------------- ### Apply Kilo PodMonitor Source: https://github.com/squat/kilo/blob/main/docs/monitoring.md Apply the PodMonitor configuration to monitor the Kilo DaemonSet. This requires the kube-prometheus monitoring stack to be installed. ```shell kubectl apply -f https://raw.githubusercontent.com/squat/kilo/main/manifests/podmonitor.yaml ``` -------------------------------- ### Configure QEMU for Multi-Architecture Builds Source: https://github.com/squat/kilo/blob/main/docs/building_kilo.md Configure QEMU as the interpreter for binaries built for non-native architectures when building Docker containers. ```shell docker run --rm --privileged multiarch/qemu-user-static --reset -p yes ``` -------------------------------- ### Install Kilo as Add-on on Typhoon with Flannel Source: https://github.com/squat/kilo/blob/main/README.md Apply CRDs and Kilo DaemonSet for running Kilo in add-on mode on Typhoon with Flannel. ```shell kubectl apply -f https://raw.githubusercontent.com/squat/kilo/main/manifests/crds.yaml kubectl apply -f https://raw.githubusercontent.com/squat/kilo/main/manifests/kilo-typhoon-flannel.yaml ``` -------------------------------- ### Structured vs. Unstructured Logging Source: https://github.com/squat/kilo/blob/main/vendor/github.com/go-kit/kit/log/README.md Illustrates the difference between unstructured and structured logging formats. Structured logging uses key/value pairs for contextual information. ```go // Unstructured log.Printf("HTTP server listening on %s", addr) // Structured logger.Log("transport", "HTTP", "addr", addr, "msg", "listening") ``` -------------------------------- ### Get Flag Value from FlagSet Source: https://github.com/squat/kilo/blob/main/vendor/github.com/spf13/pflag/README.md Retrieve the integer value of a flag from a FlagSet using GetInt(). This requires the flag to exist and be of the correct type. ```go i, err := flagset.GetInt("flagname") ``` -------------------------------- ### Execute Unit Tests Source: https://github.com/squat/kilo/blob/main/docs/building_kilo.md Run all unit tests for the Kilo project using the Make command. ```shell make unit ```