### Install Blackfriday v2 Source: https://github.com/knative/eventing/blob/main/vendor/github.com/russross/blackfriday/v2/README.md Use 'go get' to install the package in module mode. Alternatively, import it in your package and run 'go get'. ```go go get github.com/russross/blackfriday/v2 ``` -------------------------------- ### Install OTLP Prometheus Translator Source: https://github.com/knative/eventing/blob/main/vendor/github.com/prometheus/otlptranslator/README.md Install the library using go get. ```bash go get github.com/prometheus/otlptranslator ``` -------------------------------- ### Install go.yaml.in/yaml/v3 Source: https://github.com/knative/eventing/blob/main/vendor/go.yaml.in/yaml/v3/README.md Use 'go get' to install the package. The import path is go.yaml.in/yaml/v3. ```bash go get go.yaml.in/yaml/v3 ``` -------------------------------- ### Main function for Webhook Setup Source: https://github.com/knative/eventing/blob/main/vendor/knative.dev/pkg/webhook/README.md Sets up the webhook server with signal context and options, then starts the main process using `sharedmain.MainWithContext`. It includes the certificate controller and the resource admission controller. ```go func main() { // Set up a signal context with our webhook options. ctx := webhook.WithOptions(signals.NewContext(), webhook.Options{ // The name of the Kubernetes service selecting over this deployment's pods. ServiceName: "webhook", // The port on which to serve. Port: 8443, // The name of the secret containing certificate data. SecretName: "webhook-certs", }) sharedmain.MainWithContext(ctx, "webhook", // The certificate controller will ensure that the named secret (above) has // the appropriate shape for our webhook's admission controllers. certificates.NewController, // This invokes the method defined above to instantiate the resource admission // controller. NewResourceAdmissionController, ) } ``` -------------------------------- ### Install Cobra Library Source: https://github.com/knative/eventing/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 blackfriday-tool Source: https://github.com/knative/eventing/blob/main/vendor/github.com/russross/blackfriday/v2/README.md Install the blackfriday-tool command-line utility using 'go get'. This tool provides a standalone program for processing markdown files. ```go go get github.com/russross/blackfriday-tool ``` -------------------------------- ### Starting Controllers with Shared Main Source: https://github.com/knative/eventing/blob/main/vendor/knative.dev/pkg/injection/README.md Use `sharedmain.Main` to start controllers by passing their constructors and a component name. This function handles the setup and running of injected controllers. ```go package main import ( // The set of controllers this process will run. "github.com/knative/foo/pkg/reconciler/bar" "github.com/knative/baz/pkg/reconciler/blah" // This defines the shared main for injected controllers. "knative.dev/pkg/injection/sharedmain" ) func main() { sharedmain.Main("componentname", bar.NewController, blah.NewController, ) } ``` -------------------------------- ### Define a RESTful WebService and Route Source: https://github.com/knative/eventing/blob/main/vendor/github.com/emicklei/go-restful/v3/README.md Example demonstrating how to create a new WebService, define its path, supported content types, and a GET route for retrieving a user. This includes setting up path parameters and specifying the 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 Flect Package Source: https://github.com/knative/eventing/blob/main/vendor/github.com/gobuffalo/flect/README.md Use `go get` to install the Flect package into your Go project. ```console go get github.com/gobuffalo/flect ``` -------------------------------- ### Install multierr Source: https://github.com/knative/eventing/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 json-iterator/go Source: https://github.com/knative/eventing/blob/main/vendor/github.com/json-iterator/go/README.md Use the go get command to install the json-iterator/go library into your project. ```bash go get github.com/json-iterator/go ``` -------------------------------- ### Install and Run Local Go Doc Site Source: https://github.com/knative/eventing/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Installs the pkgsite tool and runs a local Go documentation site. This is useful for previewing package documentation. ```sh go install golang.org/x/pkgsite/cmd/pkgsite@latest pkgsite ``` -------------------------------- ### Build FreePort from Source Source: https://github.com/knative/eventing/blob/main/vendor/github.com/phayes/freeport/README.md Build FreePort from source by first installing Go and then using 'go get' to download and install the package. This method is suitable for development or when pre-built packages are unavailable. ```bash sudo apt-get install golang # Download go. Alternativly build from source: https://golang.org/doc/install/source go get github.com/phayes/freeport ``` -------------------------------- ### Perform Quick Full Build and Install Source: https://github.com/knative/eventing/blob/main/DEVELOPMENT.md Use this script for a complete build and installation of Eventing components. It builds container images for your local architecture by default. ```shell ./hack/install.sh ``` -------------------------------- ### Install go.uber.org/atomic Source: https://github.com/knative/eventing/blob/main/vendor/go.uber.org/atomic/README.md Use 'go get' to install the latest version of the atomic package. ```shell go get -u go.uber.org/atomic@v1 ``` -------------------------------- ### Set Environment Variables for Usage Example Source: https://github.com/knative/eventing/blob/main/vendor/github.com/kelseyhightower/envconfig/README.md Example environment variables to be loaded into a Go struct. ```Bash export MYAPP_DEBUG=false export MYAPP_PORT=8080 export MYAPP_USER=Kelsey export MYAPP_RATE="0.5" export MYAPP_TIMEOUT="3m" export MYAPP_USERS="rob,ken,robert" export MYAPP_COLORCODES="red:1,green:2,blue:3" ``` -------------------------------- ### Deterministic Testing Setup Source: https://github.com/knative/eventing/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Use deterministic testing with isolated state. This example shows how to restore global state after a test, isolate the meter provider, set environment variables, and reset counters for deterministic testing. ```go func TestObservability(t *testing.T) { // Restore state after test to ensure this does not affect other tests. prev := otel.GetMeterProvider() t.Cleanup(func() { otel.SetMeterProvider(prev) }) // Isolate the meter provider for deterministic testing reader := metric.NewManualReader() meterProvider := metric.NewMeterProvider(metric.WithReader(reader)) otel.SetMeterProvider(meterProvider) // Use t.Setenv to ensure environment variable is restored after test. t.Setenv("OTEL_GO_X_OBSERVABILITY", "true") // Reset component ID counter to ensure deterministic component names. componentIDCounter.Store(0) /* ... test code ... */ } ``` -------------------------------- ### Merge Patch Output Example Source: https://github.com/knative/eventing/blob/main/vendor/gopkg.in/evanphx/json-patch.v4/README.md Example output when running the Go code to create and apply a merge patch. ```bash $ go run main.go patch document: {"height":null,"name":"Jane"} updated alternative doc: {"age":28,"name":"Jane"} ``` -------------------------------- ### Create Demo In-Memory Channel Source: https://github.com/knative/eventing/blob/main/config/channels/in-memory-channel/README.md Installs an In-Memory Channel named 'demo' for demonstration purposes. Requires core Eventing to be installed for subscriptions. ```yaml apiVersion: messaging.knative.dev/v1 kind: InMemoryChannel metadata: name: demo ``` -------------------------------- ### Install MT Channel Based Broker Source: https://github.com/knative/eventing/blob/main/docs/broker/README.md Installs the Multi Tenant Channel Based Broker implementation. Requires Knative Eventing core to be installed first. ```bash ko apply -f config/brokers/mt-channel-broker/ ``` -------------------------------- ### Explicit Instrumentation Setup Source: https://github.com/knative/eventing/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Demonstrates explicit and side-effect-free initialization of instrumentation within a component's constructor. This pattern ensures clear ownership and scope for observability setup. ```go import ( "errors" semconv "go.opentelemetry.io/otel/semconv/v1.41.0" "go.opentelemetry.io/otel/semconv/v1.41.0/otelconv" ) type SDKComponent struct { inst *instrumentation } func NewSDKComponent(config Config) (*SDKComponent, error) { inst, err := newInstrumentation() if err != nil { return nil, err } return &SDKComponent{inst: inst}, nil } type instrumentation struct { inflight otelconv.SDKComponentInflight exported otelconv.SDKComponentExported } func newInstrumentation() (*instrumentation, error) { if !x.Observability.Enabled() { return nil, nil } meter := otel.GetMeterProvider().Meter( "", metric.WithInstrumentationVersion(sdk.Version()), metric.WithSchemaURL(semconv.SchemaURL), ) inst := &instrumentation{} var err, e error inst.inflight, e = otelconv.NewSDKComponentInflight(meter) err = errors.Join(err, e) inst.exported, e = otelconv.NewSDKComponentExported(meter) err = errors.Join(err, e) return inst, err } ``` -------------------------------- ### Install MT Channel Broker Source: https://github.com/knative/eventing/blob/main/DEVELOPMENT.md Installs the MT Channel Broker using the 'ko apply' command. This is a common step for setting up eventing capabilities. ```shell ko apply -f config/brokers/mt-channel-broker/ ``` -------------------------------- ### Install jsontoml tool Source: https://github.com/knative/eventing/blob/main/vendor/github.com/pelletier/go-toml/v2/README.md Installs the jsontoml command-line tool. Use this to convert JSON files to TOML. ```bash go install github.com/pelletier/go-toml/v2/cmd/jsontoml@latest jsontoml --help ``` -------------------------------- ### Install uuid Package Source: https://github.com/knative/eventing/blob/main/vendor/github.com/google/uuid/README.md Use this command to install the uuid package for your Go project. ```sh go get github.com/google/uuid ``` -------------------------------- ### Install tomljson tool Source: https://github.com/knative/eventing/blob/main/vendor/github.com/pelletier/go-toml/v2/README.md Installs the tomljson command-line tool. Use this to convert TOML files to JSON. ```bash go install github.com/pelletier/go-toml/v2/cmd/tomljson@latest tomljson --help ``` -------------------------------- ### Install tomll tool Source: https://github.com/knative/eventing/blob/main/vendor/github.com/pelletier/go-toml/v2/README.md Installs the tomll command-line tool. Use this to lint and reformat TOML files. ```bash go install github.com/pelletier/go-toml/v2/cmd/tomll@latest tomll --help ``` -------------------------------- ### ConfigStore Integration in NewImpl Source: https://github.com/knative/eventing/blob/main/vendor/knative.dev/pkg/injection/README.md Demonstrates how to integrate ConfigStore into a generated reconciler by passing it during the NewImpl setup. ```go kindreconciler "knative.dev//pkg/client/injection/reconciler///" ... impl := kindreconciler.NewImpl(ctx, c, func(impl *controller.Impl) controller.Options { // Setup options that require access to a controller.Impl. configsToResync := []interface{}{ &some.Config{}, } resyncOnConfigChange := configmap.TypeFilter(configsToResync...)(func(string, interface{}) { impl.FilteredGlobalResync(myFilterFunc, kindInformer.Informer()) }) configStore := config.NewStore(c.Logger.Named("config-store"), resyncOnConfigChange) configStore.WatchConfigs(cmw) // Return the controller options. return controller.Options{ ConfigStore: configStore, } }) ``` -------------------------------- ### Install In-Memory Channel Source: https://github.com/knative/eventing/blob/main/DEVELOPMENT.md Deploy the default In-Memory Channel implementation using 'ko apply' with the channel's configuration directory. ```shell ko apply -Rf config/channels/in-memory-channel/ ``` -------------------------------- ### Create Root Logger Source: https://github.com/knative/eventing/blob/main/vendor/github.com/go-logr/logr/README.md Initialize the root logger early in application setup, choosing a specific logging implementation. ```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 ... } ``` -------------------------------- ### Probe Test Setup Diagram Source: https://github.com/knative/eventing/blob/main/test/upgrade/README.md Illustrates the architecture of the probe test setup, which verifies data-plane unavailability during control-plane outages by sending and verifying events. ```text K8s cluster | Test machine | (deployment) (ksvc) (deployment) | +--------+ +-----------+ +----------+ | | | | ++ | | | | Sender | +-->| Forwarder ||----->+ Receiver | | | | | | || | |<---+ | +---+----+ | +------------| +----------+ | | | +-----------+ | | ```````|````````````````````````````` | | ` | ` +---------+ | | ` +--+-----+ +---------+ ` | | | +-----> | | +-+ ` | Fetcher | | ` | Broker | < - > | Trigger | | ` | | | ` | | | | | ` +---------+ | ` +--------+ +---------+ | ` (job) | ` (default) +----------+ ` | ` (SUT) ` ````````````````````````````````````` ``` -------------------------------- ### Initialize Procfs Filesystem Source: https://github.com/knative/eventing/blob/main/vendor/github.com/prometheus/procfs/README.md Initializes the proc filesystem and retrieves CPU statistics. Use this to start interacting with procfs data. ```go fs, err := procfs.NewFS("/proc") stats, err := fs.Stat() ``` -------------------------------- ### Basic Controller Constructor Source: https://github.com/knative/eventing/blob/main/vendor/knative.dev/pkg/injection/README.md Implementations should start with this controller constructor. It sets up the logger and initializes the reconciler. ```go import ( "context" "knative.dev/pkg/configmap" "knative.dev/pkg/controller" "knative.dev/pkg/logging" kindreconciler "knative.dev//pkg/client/injection/reconciler///" ) func NewController(ctx context.Context, cmw configmap.Watcher) *controller.Impl { logger := logging.FromContext(ctx) // TODO(you): Access informers r := &Reconciler{ // TODO(you): Pass listers, clients, and other stuff. } impl := kindreconciler.NewImpl(ctx, r) // TODO(you): Set up event handlers. return impl } ``` -------------------------------- ### Add or Update Dependency Source: https://github.com/knative/eventing/blob/main/vendor/github.com/prometheus/procfs/CONTRIBUTING.md Use 'go get' to add or update external packages. Dependencies are vendored in the 'vendor/' directory. ```bash # Pick the latest tagged release. go get example.com/some/module/pkg # Pick a specific version. go get example.com/some/module/pkg@vX.Y.Z ``` -------------------------------- ### Instantiation with Options Source: https://github.com/knative/eventing/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Demonstrates how to instantiate a type using a variadic slice of Option parameters. ```go func NewT(options ...Option) T {…} ``` -------------------------------- ### Install Latest JSON-Patch v5 Source: https://github.com/knative/eventing/blob/main/vendor/gopkg.in/evanphx/json-patch.v4/README.md Use this command to get the latest version of the jsonpatch library for Go. ```bash go get -u github.com/evanphx/json-patch/v5 ``` -------------------------------- ### Setup Zap Repository Source: https://github.com/knative/eventing/blob/main/vendor/go.uber.org/zap/CONTRIBUTING.md Clone the Zap repository and set up the upstream remote for contributing. Ensure your Go environment is configured correctly. ```bash mkdir -p $GOPATH/src/go.uber.org cd $GOPATH/src/go.uber.org git clone git@github.com:your_github_username/zap.git cd zap git remote add upstream https://github.com/uber-go/zap.git git fetch upstream ``` -------------------------------- ### Enable Stub Generation with +genreconciler:stubs Source: https://github.com/knative/eventing/blob/main/vendor/knative.dev/pkg/injection/README.md Add the +genreconciler:stubs annotation to generate basic stub implementations for controllers. These are intended for getting started or as reference. ```go // +genreconciler:stubs ``` -------------------------------- ### Sample Release Script Implementation Source: https://github.com/knative/eventing/blob/main/vendor/knative.dev/hack/README.md A sample `release.sh` script demonstrating how to define the `build_release` function and call the `main` function. It shows how to use `ko resolve` to build release artifacts. ```bash source "$(go run knative.dev/hack/cmd/script release.sh)" function build_release() { # config/ contains the manifests ko resolve ${KO_FLAGS} -f config/ > release.yaml ARTIFACTS_TO_PUBLISH="release.yaml" } main "$@" ``` -------------------------------- ### Filter Controller Promotion with PromoteFilterFunc Source: https://github.com/knative/eventing/blob/main/vendor/knative.dev/pkg/injection/README.md Pass a PromoteFilterFunc to the controller's constructor to filter which objects get reconciled upon promotion. This example uses a label filter. ```go kindreconciler "knative.dev//pkg/client/injection/reconciler///" pkgreconciler "knative.dev/pkg/reconciler" ... impl := kindreconciler.NewImpl(ctx, c, func(impl *controller.Impl) controller.Options { return controller.Options{ PromoteFilterFunc: pkgreconciler.LabelFilterFunc("mylabel", "myvalue", false), } }) ``` -------------------------------- ### Run E2E Tests Skipping Knative Setup Source: https://github.com/knative/eventing/blob/main/test/README.md Execute end-to-end tests on a pre-configured environment that meets the e2e test requirements, skipping Knative installation. Requires PROJECT_ID to be set. ```shell test/e2e-tests.sh --run-tests --skip-knative-setup --gcp-project-id=$PROJECT_ID ``` -------------------------------- ### NewConfig Function Example Source: https://github.com/knative/eventing/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Demonstrates a common pattern for creating a configuration struct by wrapping default settings and applying options. This function is typically unexported. ```go // newConfig returns an appropriately configured config. func newConfig(options ...Option) config { // Set default values for config. config := config{/* […] */} for _, option := range options { config = option.apply(config) } // Perform any validation here. return config } ``` -------------------------------- ### Basic glog Usage Examples Source: https://github.com/knative/eventing/blob/main/vendor/k8s.io/klog/README.md Illustrates fundamental logging operations using glog. Use Info for general messages and Fatalf for critical errors that should halt execution. ```go glog.Info("Prepare to repel boarders") glog.Fatalf("Initialization failed: %s", err) ``` -------------------------------- ### Install FreePort on Ubuntu/DEB Systems Source: https://github.com/knative/eventing/blob/main/vendor/github.com/phayes/freeport/README.md Install FreePort on Ubuntu and other Debian-based Linux distributions by downloading and installing the provided DEB package. ```bash wget wget https://github.com/phayes/freeport/releases/download/1.0.2/freeport_1.0.2_linux_amd64.deb dpkg -i freeport_1.0.2_linux_amd64.deb ``` -------------------------------- ### Example using TagSet and TagOptions Source: https://github.com/knative/eventing/blob/main/vendor/github.com/fxamacker/cbor/v2/README.md Shows how to create a `TagSet`, register a custom type for a specific tag number, and then use this `TagSet` to create decoding and encoding modes for handling tagged CBOR data. ```go // Use signedCWT struct defined in "Decoding CWT" example. // Create TagSet (safe for concurrency). tags := cbor.NewTagSet() // Register tag COSE_Sign1 18 with signedCWT type. tags.Add( 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 FreePort on CentOS/RPM Systems Source: https://github.com/knative/eventing/blob/main/vendor/github.com/phayes/freeport/README.md Install FreePort on CentOS and other RPM-based Linux distributions by downloading and installing the provided RPM package. ```bash wget https://github.com/phayes/freeport/releases/download/1.0.2/freeport_1.0.2_linux_386.rpm rpm -Uvh freeport_1.0.2_linux_386.rpm ``` -------------------------------- ### Install Cert-Manager Trust-Manager Source: https://github.com/knative/eventing/blob/main/DEVELOPMENT.md Applies the Trust-manager component of Cert-manager. This is the final step after installing the core components. ```shell kubectl apply -f third_party/cert-manager/02-trust-manager.yaml ``` -------------------------------- ### Install Cobra CLI Generator Source: https://github.com/knative/eventing/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 FreePort on Mac OSX Source: https://github.com/knative/eventing/blob/main/vendor/github.com/phayes/freeport/README.md Install the FreePort utility on macOS using Homebrew. This is the recommended method for Mac users. ```bash brew install phayes/repo/freeport ``` -------------------------------- ### Basic fsnotify Watcher Usage in Go Source: https://github.com/knative/eventing/blob/main/vendor/github.com/fsnotify/fsnotify/README.md Demonstrates how to create a new watcher, listen for events and errors in a separate goroutine, add a directory to watch, and handle potential errors. Ensure the watcher's channels are processed to avoid deadlocks. ```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{}) } ``` -------------------------------- ### Initialize Block Device Filesystem Source: https://github.com/knative/eventing/blob/main/vendor/github.com/prometheus/procfs/README.md Initializes a filesystem instance that requires access to both /proc and /sys. This is used for components like block devices. ```go fs, err := blockdevice.NewFS("/proc", "/sys") stats, err := fs.ProcDiskstats() ``` -------------------------------- ### Sample End-to-End Test Script Source: https://github.com/knative/eventing/blob/main/vendor/knative.dev/hack/README.md A sample script demonstrating how to use the e2e-tests.sh helper for testing Knative Serving. It includes custom functions for setup and flag parsing, and initializes the test cluster. ```bash source "$(go run knative.dev/hack/cmd/script e2e-tests.sh)" function knative_setup() { start_latest_knative_serving if (( WAIT_FOR_KNATIVE )); then wait_until_pods_running knative-serving || fail_test "Knative Serving not up" fi } function parse_flags() { if [[ "$1" == "--no-knative-wait" ]]; then WAIT_FOR_KNATIVE=0 return 1 fi return 0 } WAIT_FOR_KNATIVE=1 # This test requires a cluster in LA initialize $@ --region=us-west2 # TODO: use go_test_e2e to run the tests. kubectl get pods || fail_test success ``` -------------------------------- ### Get OpenTelemetry Go Repository Source: https://github.com/knative/eventing/blob/main/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Use 'go get' to download the OpenTelemetry Go source code. This command may produce warnings that can be ignored. ```sh go get -d go.opentelemetry.io/otel ``` -------------------------------- ### Sample performance test script Source: https://github.com/knative/eventing/blob/main/vendor/knative.dev/hack/README.md This sample script demonstrates how to use the `performance-tests.sh` helper. It defines functions to update Knative serving and a specific benchmark, then calls the main function to execute them. ```bash source "$(go run knative.dev/hack/cmd/script performance-tests.sh)" function update_knative() { echo ">> Updating serving" ko apply -f config/ || abort "failed to apply serving" } function update_benchmark() { echo ">> Updating benchmark $1" ko apply -f ${BENCHMARK_ROOT_PATH}/$1 || abort "failed to apply benchmark $1" } main $@ ``` -------------------------------- ### Basic GET Request with go-retryablehttp Source: https://github.com/knative/eventing/blob/main/vendor/github.com/hashicorp/go-retryablehttp/README.md Demonstrates a simple GET request using the retryablehttp client. If the request fails, it will automatically retry with exponential backoff. ```go resp, err := retryablehttp.Get("/foo") if err != nil { panic(err) } ``` -------------------------------- ### Basic glog Usage Source: https://github.com/knative/eventing/blob/main/vendor/k8s.io/klog/v2/README.md Demonstrates basic logging functions like Info and Fatalf. Use Fatalf for critical errors that should stop execution. ```go glog.Info("Prepare to repel boarders") ``` ```go glog.Fatalf("Initialization failed: %s", err) ``` -------------------------------- ### Example Composed Filter with AND Source: https://github.com/knative/eventing/blob/main/docs/broker/filtering.md Illustrates a potential future design for structured filter composition using 'and' to combine multiple filter conditions. This is an example and not currently part of the proposal. ```yaml spec: filter: and: - attributes: type: com.github.pull.create - expression: ce.source.match("knative") ``` -------------------------------- ### Initialize Controller Implementation with NewImpl Source: https://github.com/knative/eventing/blob/main/vendor/knative.dev/pkg/injection/README.md The NewImpl function gets an injection-based client and lister, sets up Kubernetes Event recorders, and delegates to controller.NewContext for queue management. ```go impl := reconciler.NewImpl(ctx, reconcilerInstance) ``` -------------------------------- ### Structured Filters Example (YAML) Source: https://github.com/knative/eventing/blob/main/docs/broker/filtering.md Demonstrates structured filters using YAML, similar to Kubernetes set-based label selectors, for defining match expressions. ```yaml matchExpressions: - {key: tier, operator: In, values: [cache]} - {key: environment, operator: NotIn, values: [dev]} ``` -------------------------------- ### Even Slice Length Validator Example Source: https://github.com/knative/eventing/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 uses Go generics to support 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 ``` -------------------------------- ### Map Keys Max Length Validator Example Source: https://github.com/knative/eventing/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 accepts a maximum length integer as an additional argument. ```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 ``` -------------------------------- ### NonEmpty String Validator Example Source: https://github.com/knative/eventing/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 adheres to the standard signature, taking context, operation, field path, and a pointer to the string value. ```go // NonEmpty validates that a string is not empty. func NonEmpty(ctx context.Context, op operation.Operation, fldPath *field.Path, value, _ *string) field.ErrorList ``` -------------------------------- ### Quick Start: OTLP to Prometheus Translation Source: https://github.com/knative/eventing/blob/main/vendor/github.com/prometheus/otlptranslator/README.md Demonstrates creating a metric namer with a specific strategy and translating an OTLP metric and label names to Prometheus format. ```go package main import ( "fmt" "github.com/prometheus/otlptranslator" ) func main() { // Create a metric namer using traditional Prometheus name translation, with suffixes added and UTF-8 disallowed. strategy := otlptranslator.UnderscoreEscapingWithSuffixes namer := otlptranslator.NewMetricNamer("myapp", strategy) // Translate OTLP metric to Prometheus format metric := otlptranslator.Metric{ Name: "http.server.request.duration", Unit: "s", Type: otlptranslator.MetricTypeHistogram, } fmt.Println(namer.Build(metric)) // Output: myapp_http_server_request_duration_seconds // Translate label names labelNamer := otlptranslator.LabelNamer{UTF8Allowed: false} fmt.Println(labelNamer.Build("http.method")) // Output: http_method } ```