### Named Tracer Setup Example Source: https://github.com/kubernetes/dns/blob/master/vendor/go.opentelemetry.io/otel/CHANGELOG.md Example demonstrating how to get a tracer instance with a specific name. This is useful for organizing and filtering traces. ```go package main import ( "context" "log" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/exporters/stdout/stdouttrace" "go.opentelemetry.io/otel/sdk/resource" "go.opentelemetry.io/otel/sdk/trace" ) func main() { ctx := context.Background() // Set up a tracer provider with a stdout exporter. exporter, err := stdouttrace.New(stdouttrace.WithPrettyPrint()) if err != nil { log.Fatalf("failed to initialize stdouttrace exporter: %v", err) } res, err := resource.New(ctx) if err != nil { log.Fatalf("failed to create resource: %v", err) } tracerProvider := trace.NewTracerProvider( trace.WithBatcher(exporter), trace.WithResource(res), ) otel.SetTracerProvider(tracerProvider) defer func() { if err := tracerProvider.Shutdown(ctx); err != nil { log.Printf("failed to shutdown TracerProvider: %v", err) } }() // Get a tracer instance with a specific name. tracer := otel.Tracer("my-named-tracer") // Start a span using the named tracer. ctx, span := tracer.Start(ctx, "named-operation") defer span.End() span.AddEvent("event from named tracer") log.Println("Named tracer operation completed") } ``` -------------------------------- ### Install miekg/dns Library Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/miekg/dns/README.md Use the go get command to install the library. This command fetches and installs the package and its dependencies. ```go go get github.com/miekg/dns ``` -------------------------------- ### Setup Ginkgo and Gomega Dependencies Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/onsi/ginkgo/CONTRIBUTING.md Installs the Ginkgo and Gomega libraries using go get. Ensure you are in the correct GOPATH directory before running. ```bash go get github.com/onsi/ginkgo go get github.com/onsi/gomega/... ``` -------------------------------- ### Install go-version Library Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/hashicorp/go-version/README.md Install the go-version library using the standard go get command. ```bash $ go get github.com/hashicorp/go-version ``` -------------------------------- ### Basic HTTP Tracer Setup Example Source: https://github.com/kubernetes/dns/blob/master/vendor/go.opentelemetry.io/otel/CHANGELOG.md Example code for setting up a basic HTTP tracer. This snippet is part of a larger set of examples for different tracer configurations. ```go package main import ( "context" "log" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/exporters/stdout/stdouttrace" "go.opentelemetry.io/otel/sdk/resource" "go.opentelemetry.io/otel/sdk/trace" "go.opentelemetry.io/otel/trace" ) func main() { ctx := context.Background() // Set up a tracer provider with a stdout exporter. exporter, err := stdouttrace.New(stdouttrace.WithPrettyPrint()) if err != nil { log.Fatalf("failed to initialize stdouttrace exporter: %v", err) } // For the purpose of this example, we use a noop resource. // In a real application, this would contain information about the service. res, err := resource.New(ctx, resource.WithAttributes( // Example attributes // attribute.String("service.name", "my-service"), // attribute.String("version", "1.0.0"), ), ) if err != nil { log.Fatalf("failed to create resource: %v", err) } // Create a new tracer provider with the exporter and resource. tracerProvider := trace.NewTracerProvider( trace.WithBatcher(exporter), trace.WithResource(res), ) // Set the global tracer provider. otel.SetTracerProvider(tracerProvider) // Defer closing the tracer provider until the program exits. defer func() { if err := tracerProvider.Shutdown(ctx); err != nil { log.Printf("failed to shutdown TracerProvider: %v", err) } }() // Get a tracer instance. tracer := otel.Tracer("my-tracer-name") // Start a new span. ctx, span := tracer.Start(ctx, "my-operation") defer span.End() // Your application logic here... span.AddEvent("event in my-operation") // Simulate some work // time.Sleep(100 * time.Millisecond) log.Println("Trace completed") } ``` -------------------------------- ### Install go-isatty package Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/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 etcd/client/v3 Source: https://github.com/kubernetes/dns/blob/master/vendor/go.etcd.io/etcd/client/v3/README.md Use 'go get' to install the etcd/client/v3 package. This is recommended for full compatibility with released versions. ```bash go get go.etcd.io/etcd/client/v3 ``` -------------------------------- ### Install go-sqllexer Library Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/DataDog/go-sqllexer/README.md Use 'go get' to install the go-sqllexer library for use in your Go projects. ```bash go get github.com/DataDog/go-sqllexer ``` -------------------------------- ### Install and Test Go OLE Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/go-ole/go-ole/README.md Instructions for installing the go-ole library, running tests, and executing an example program for Excel integration. Ensure you navigate to the correct directories before running commands. ```bash go get github.com/go-ole/go-ole cd /path/to/go-ole/ go test cd /path/to/go-ole/example/excel go run excel.go ``` -------------------------------- ### HTTP Stackdriver Tracer Setup Example Source: https://github.com/kubernetes/dns/blob/master/vendor/go.opentelemetry.io/otel/CHANGELOG.md Example code for setting up an HTTP tracer with Stackdriver export. This demonstrates integration with Google Cloud's operations suite. ```go package main import ( "context" "log" "go.opentelemetry.io/contrib/exporters/metric/google/googlemetric" "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/sdk/resource" "go.opentelemetry.io/otel/sdk/metric" "go.opentelemetry.io/otel/sdk/trace" // "go.opentelemetry.io/otel/attribute" ) func main() { ctx := context.Background() // Set up a metric provider with a Stackdriver exporter. metricExporter, err := googlemetric.NewExporter(ctx, // googlemetric.WithProjectID("your-gcp-project-id"), // Uncomment and set your project ID ) if err != nil { log.Fatalf("failed to initialize Stackdriver metric exporter: %v", err) } // For the purpose of this example, we use a noop resource. // In a real application, this would contain information about the service. res, err := resource.New(ctx, // resource.WithAttributes( // attribute.String("service.name", "my-service"), // attribute.String("version", "1.0.0"), // ), ) if err != nil { log.Fatalf("failed to create resource: %v", err) } metricProvider := metric.NewMeterProvider( metric.WithReader(metric.NewPeriodicReader(metricExporter)), metric.WithResource(res), ) // Defer shutting down the metric provider. defer func() { if err := metricProvider.Shutdown(ctx); err != nil { log.Printf("failed to shutdown MeterProvider: %v", err) } }() // Set the global metric provider. otel.SetMeterProvider(metricProvider) // Set up a tracer provider with a Stackdriver exporter. // Note: Stackdriver trace exporter is typically configured separately or via environment variables. // For simplicity, this example focuses on metric export and uses a stdout exporter for traces. // In a real scenario, you would configure the trace exporter similarly to the metric exporter. traceExporter, err := stdouttrace.New(stdouttrace.WithPrettyPrint()) if err != nil { log.Fatalf("failed to initialize stdouttrace exporter: %v", err) } tracerProvider := trace.NewTracerProvider( trace.WithBatcher(traceExporter), trace.WithResource(res), ) // Set the global tracer provider. otel.SetTracerProvider(tracerProvider) // Defer closing the tracer provider. defer func() { if err := tracerProvider.Shutdown(ctx); err != nil { log.Printf("failed to shutdown TracerProvider: %v", err) } }() // Use otelhttp to instrument HTTP clients and servers. // This will automatically create spans for incoming and outgoing HTTP requests. http.Handle("/", otelhttp.NewHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello, world!")) }), "hello")) log.Println("Serving on :8080") log.Fatal(http.ListenAndServe(":8080", nil)) } ``` -------------------------------- ### Jaeger Tracer Setup Example Source: https://github.com/kubernetes/dns/blob/master/vendor/go.opentelemetry.io/otel/CHANGELOG.md Example code for setting up a tracer that exports to Jaeger. This requires a running Jaeger agent or collector. ```go package main import ( "context" "log" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/exporters/jaeger" "go.opentelemetry.io/otel/sdk/resource" "go.opentelemetry.io/otel/sdk/trace" "go.opentelemetry.io/otel/attribute" ) func main() { ctx := context.Background() // Set up a Jaeger exporter. // Replace "http://localhost:14268/api/traces" with your Jaeger endpoint if it's different. jExp, err := jaeger.New(jaeger.WithCollectorEndpoint(jaeger.WithEndpoint("http://localhost:14268/api/traces"))) if err != nil { log.Fatalf("failed to create Jaeger exporter: %v", err) } // For the purpose of this example, we use a noop resource. // In a real application, this would contain information about the service. res, err := resource.New(ctx, resource.WithAttributes( attribute.String("service.name", "my-jaeger-service"), attribute.String("exporter", "jaeger"), ), ) if err != nil { log.Fatalf("failed to create resource: %v", err) } // Create a tracer provider with the Jaeger exporter. tracerProvider := trace.NewTracerProvider( trace.WithBatcher(jExp), trace.WithResource(res), ) // Set the global tracer provider. otel.SetTracerProvider(tracerProvider) // Defer shutting down the tracer provider. defer func() { if err := tracerProvider.Shutdown(ctx); err != nil { log.Printf("failed to shutdown TracerProvider: %v", err) } }() // Get a tracer instance. racer := otel.Tracer("my-tracer-name") // Start a new span. ctx, span := tracer.Start(ctx, "my-jaeger-operation") defer span.End() // Your application logic here... span.AddEvent("event in my-jaeger-operation") log.Println("Trace sent to Jaeger") } ``` -------------------------------- ### Install Seelog using Go Get Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/cihub/seelog/README.markdown Command to install the Seelog library using Go's package management tool. This command fetches and installs the latest version. ```bash go get -u github.com/cihub/seelog ``` -------------------------------- ### Install go.yaml.in/yaml/v3 Source: https://github.com/kubernetes/dns/blob/master/vendor/go.yaml.in/yaml/v3/README.md Use 'go get' to install the YAML package for Go. This command fetches and installs the specified package and its dependencies. ```bash go get go.yaml.in/yaml/v3 ``` -------------------------------- ### Install otgrpc package Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/grpc-ecosystem/grpc-opentracing/go/otgrpc/README.md Use 'go get' to install the otgrpc package for OpenTracing support in gRPC. ```bash go get github.com/grpc-ecosystem/grpc-opentracing/go/otgrpc ``` -------------------------------- ### Install and Run Local Go Doc Site Source: https://github.com/kubernetes/dns/blob/master/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Installs and runs a local Go Doc site using pkgsite. Ensure you have Go installed and configured. ```sh go install golang.org/x/pkgsite/cmd/pkgsite@latest pkgsite ``` -------------------------------- ### Install go-colorable Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/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 json-iterator/go Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/json-iterator/go/README.md Use go get to install the json-iterator/go package. ```bash go get github.com/json-iterator/go ``` -------------------------------- ### Install YAML Package for Go Source: https://github.com/kubernetes/dns/blob/master/vendor/gopkg.in/yaml.v3/README.md Use 'go get' to install the yaml.v3 package. This command fetches and installs the specified package and its dependencies. ```bash go get gopkg.in/yaml.v3 ``` -------------------------------- ### Add stdoutlog exporter example Source: https://github.com/kubernetes/dns/blob/master/vendor/go.opentelemetry.io/otel/CHANGELOG.md Example demonstrating the usage of the stdoutlog exporter. ```go go.opentelemetry.io/otel/exporters/stdout/stdoutlog ``` -------------------------------- ### CoreDNS configuration with whoami plugin Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/coredns/coredns/plugin/whoami/README.md Example Corefile configuration to start a server on the default port and load the whoami plugin for a specific domain. ```corefile example.org { whoami } ``` -------------------------------- ### Install simdjson-go Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/minio/simdjson-go/README.md Run this command to install the simdjson-go library. ```bash go get -u github.com/minio/simdjson-go ``` -------------------------------- ### Install bbloom Package Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/outcaste-io/ristretto/z/README.md Use 'go get' to install the bbloom package. Ensure your Go environment is set up correctly. ```sh go get github.com/AndreasBriese/bbloom ``` -------------------------------- ### Install go.uber.org/atomic Source: https://github.com/kubernetes/dns/blob/master/vendor/go.uber.org/atomic/README.md Install the latest version of the atomic package using go get. ```shell $ go get -u go.uber.org/atomic@v1 ``` -------------------------------- ### Install httpforwarded Package Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/theckman/httpforwarded/README.md Use 'go get' to install the httpforwarded package for use in your projects. ```bash go get -u github.com/theckman/httpforwarded ``` -------------------------------- ### Install s2c and s2d Command-line Tools Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/klauspost/compress/s2/README.md Installs the s2c (compression) and s2d (decompression) command-line tools using Go. Ensure Go is installed before running these commands. ```bash go install github.com/klauspost/compress/s2/cmd/s2c@latest && go install github.com/klauspost/compress/s2/cmd/s2d@latest ``` -------------------------------- ### Define a WebService and a Route Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/emicklei/go-restful/v3/README.md Example of creating a new WebService, setting its path and supported MIME types, and defining a GET route for retrieving a user. This snippet demonstrates basic route configuration and 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{})) ``` -------------------------------- ### Install opentracing-go observer package Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/opentracing-contrib/go-observer/README.md Fetch the observer package using go get. This is the first step to integrating the observer API into your project. ```bash go get -v github.com/opentracing-contrib/go-observer ``` -------------------------------- ### Install Cobra Library Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/spf13/cobra/README.md Use 'go get' to install the latest version of the Cobra library. This command fetches and installs the library, making it available for use in your Go projects. ```bash go get -u github.com/spf13/cobra@latest ``` -------------------------------- ### Coexist with glog Example Source: https://github.com/kubernetes/dns/blob/master/vendor/k8s.io/klog/v2/README.md Example demonstrating how to initialize and synchronize flags when using klog alongside glog. It also shows setting stderr as the combined output. ```go package main import ( "flag" "os" "k8s.io/klog/v2" ) func main() { // klog flags are registered in flag.CommandLine by default. // You can use flag.Parse() to parse the command line flags. flag.Parse() // Ensure klog flags are parsed. klog.InitFlags(nil) // Set klog to log to stderr. klog.SetOutput(os.Stderr) klog.Info("Hello, klog!") } ``` -------------------------------- ### Basic Test Script Example Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md This example demonstrates creating a new file and observing the 'create' and 'write' events. It's a fundamental example of how test scripts are structured. ```shell # Create a new empty file with some data. watch / echo data >/file Output: create /file write /file ``` -------------------------------- ### Initialize Procfs and Get Stats Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/prometheus/procfs/README.md Initializes the proc filesystem mount point and retrieves CPU statistics. Use this to start gathering metrics from /proc. ```go fs, err := procfs.NewFS("/proc") stats, err := fs.Stat() ``` -------------------------------- ### TTL Rewrite Examples with Ranges Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/coredns/coredns/plugin/rewrite/README.md Provides examples of setting TTLs using single values, ranges, capping, and minimums. ```options # rewrite TTL to be between 30s and 300s rewrite ttl example.com. 30-300 # cap TTL at 30s rewrite ttl example.com. -30 # equivalent to rewrite ttl example.com. 0-30 # increase TTL to a minimum of 30s rewrite ttl example.com. 30- # set TTL to 30s rewrite ttl example.com. 30 # equivalent to rewrite ttl example.com. 30-30 ``` -------------------------------- ### Example Corefile Configuration Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/coredns/coredns/plugin/reload/README.md This is an example of a Corefile configuration that includes the reload plugin along with other plugins like health and whoami. Be cautious when changing ports in such configurations as it might lead to reload failures. ```txt . { health :8080 whoami } ``` -------------------------------- ### Template Plugin Example: Resolve Everything to NXDOMAIN Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/coredns/coredns/plugin/template/README.md A basic example demonstrating how to configure the template plugin to respond with NXDOMAIN for all queries. This configuration uses the default zone and ensures no fallthrough occurs. ```coredns . { template ANY ANY { rcode NXDOMAIN } } ``` -------------------------------- ### Install etcd/client Go Library Source: https://github.com/kubernetes/dns/blob/master/vendor/go.etcd.io/etcd/client/v2/README.md Install the etcd/client library using go modules for full compatibility. This command fetches the latest compatible version. ```bash go get go.etcd.io/etcd/v3/client ``` -------------------------------- ### Install Ginkgo CLI Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/onsi/ginkgo/README.md Installs the Ginkgo command line interface globally. Ensure $GOBIN is in your $PATH. ```bash go get -u github.com/onsi/ginkgo/ginkgo ``` -------------------------------- ### StartOption Functions Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/DataDog/dd-trace-go/v2/ddtrace/tracer/api.txt Functions to configure Start options for the tracer. ```APIDOC ## StartOption Functions ### Description Functions to configure Start options for the tracer. ### Functions - **WithAgentAddr**(string) (StartOption) - **WithAgentTimeout**(int) (StartOption) - **WithAgentURL**(string) (StartOption) - **WithAnalytics**(bool) (StartOption) - **WithAnalyticsRate**(float64) (StartOption) - **WithAppSecEnabled**(bool) (StartOption) - **WithDebugMode**(bool) (StartOption) - **WithDebugSpansMode**(time.Duration) (StartOption) - **WithDebugStack**(bool) (StartOption) - **WithDogstatsdAddr**(string) (StartOption) - **WithEnv**(string) (StartOption) - **WithFeatureFlags**(...string) (StartOption) - **WithGlobalServiceName**(bool) (StartOption) - **WithGlobalTag**(string, interface{}) (StartOption) - **WithHTTPClient**(*http.Client) (StartOption) - **WithHeaderTags**([]string) (StartOption) - **WithHostname**(string) (StartOption) - **WithLLMObsAgentlessEnabled**(bool) (StartOption) - **WithLLMObsEnabled**(bool) (StartOption) - **WithLLMObsMLApp**(string) (StartOption) - **WithLLMObsProjectName**(string) (StartOption) - **WithLambdaMode**(bool) (StartOption) - **WithLogStartup**(bool) (StartOption) - **WithLogger**(Logger) (StartOption) - **WithPartialFlushing**(int) (StartOption) - **WithPeerServiceDefaults**(bool) (StartOption) - **WithPeerServiceMapping**(string) (StartOption) - **WithProfilerCodeHotspots**(bool) (StartOption) - **WithProfilerEndpoints**(bool) (StartOption) - **WithPropagator**(Propagator) (StartOption) - **WithRetryInterval**(int) (StartOption) - **WithRuntimeMetrics**() (StartOption) - **WithSampler**(Sampler) (StartOption) - **WithSamplerRate**(float64) (StartOption) - **WithSamplingRules**([]SamplingRule) (StartOption) - **WithSendRetries**(int) (StartOption) - **WithService**(string) (StartOption) - **WithServiceMapping**(string) (StartOption) - **WithServiceVersion**(string) (StartOption) - **WithStatsComputation**(bool) (StartOption) - **WithTestDefaults**(any) (StartOption) - **WithTraceEnabled**(bool) (StartOption) - **WithUDS**(string) (StartOption) - **WithUniversalVersion**(string) (StartOption) ``` -------------------------------- ### Add metrics to otel-collector example Source: https://github.com/kubernetes/dns/blob/master/vendor/go.opentelemetry.io/otel/CHANGELOG.md Includes metrics instrumentation within the otel-collector example. ```go go.opentelemetry.io/otel/example/dice ``` -------------------------------- ### Example Usage of go-libddwaf Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/DataDog/go-libddwaf/v4/README.md Demonstrates initializing the WAF, creating a context, and running a check with provided data. Ensure ruleset is correctly loaded and error handling is in place. ```go import waf "github.com/DataDog/go-libddwaf/v4" //go:embed var ruleset []byte func main() { var parsedRuleset any if err := json.Unmarshal(ruleset, &parsedRuleset); err != nil { panic(err) } builder, err := waf.NewBuilder("", "") if err != nil { panic(err) } _, err = builder.AddOrUpdateConfig(parsedRuleset) if err != nil { panic(err) } wafHandle := builder.Build() if wafHandle == nil { panic("WAF handle is nil") } defer wafHandle.Close() wafCtx := wafHandle.NewContext(timer.WithUnlimitedBudget(), timer.WithComponent("waf", "rasp")) defer wafCtx.Close() matches, actions := wafCtx.Run(RunAddressData{ Persistent: map[string]any{ "server.request.path_params": "/rfiinc.txt", }, TimerKey: "waf", }) } ``` -------------------------------- ### Load hosts file with specific zones and fallthrough Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/coredns/coredns/plugin/hosts/README.md This example loads 'example.hosts' but only serves 'example.org' and 'example.net'. Queries for other zones will fall through to the next plugin. ```corefile . { hosts example.hosts example.org example.net { fallthrough } } ``` -------------------------------- ### Configure and Use Ristretto Cache Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/outcaste-io/ristretto/README.md Demonstrates basic usage of the Ristretto cache, including initialization with custom configuration, setting and retrieving values, and deleting keys. Ensure proper error handling for cache initialization. ```go func main() { cache, err := ristretto.NewCache(&ristretto.Config{ NumCounters: 1e7, // number of keys to track frequency of (10M). MaxCost: 1 << 30, // maximum cost of cache (1GB). BufferItems: 64, // number of keys per Get buffer. }) if err != nil { panic(err) } // set a value with a cost of 1 cache.Set("key", "value", 1) // wait for value to pass through buffers cache.Wait() value, found := cache.Get("key") if !found { panic("missing value") } fmt.Println(value) cache.Del("key") } ``` -------------------------------- ### Basic Seelog Info Log Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/cihub/seelog/README.markdown A simple example demonstrating how to initialize Seelog and log an informational message. Ensure `log.Flush()` is called to write buffered logs. ```go package main import log "github.com/cihub/seelog" func main() { defer log.Flush() log.Info("Hello from Seelog!") } ``` -------------------------------- ### Build miekg/dns Project Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/miekg/dns/README.md Build the project using the standard Go build command. This assumes you have the Go toolchain installed. ```go go build github.com/miekg/dns ``` -------------------------------- ### Install json-patch Library Source: https://github.com/kubernetes/dns/blob/master/vendor/gopkg.in/evanphx/json-patch.v4/README.md Use this command to get the latest version of the json-patch library for your Go project. ```bash go get -u github.com/evanphx/json-patch/v5 ``` -------------------------------- ### Build Caddy with Plugins Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/coredns/caddy/README.md Use this Go program to create a custom Caddy build that includes desired plugins. Adjust the import paths to include the plugins you need. ```go package main import ( "github.com/caddyserver/caddy/caddy/caddymain" // plug in plugins here, for example: // _ "import/path/here" ) func main() { // optional: disable telemetry // caddymain.EnableTelemetry = false caddymain.Run() } ``` -------------------------------- ### Create OTLP/gRPC Trace Exporter Pipeline Source: https://github.com/kubernetes/dns/blob/master/vendor/go.opentelemetry.io/otel/CHANGELOG.md Use `otlptracegrpc.NewExportPipeline` to create and install a new OTLP/gRPC trace exporter pipeline. This function simplifies the setup process. ```go import ( "go.opentelemetry.io/otel/sdk/trace" "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc" ) // ... tracerProvider, err := trace.NewExportPipeline( trace.WithBatcher(otlptracegrpc.NewExporter()), // ... other options ) if err != nil { // handle error } // Install the tracer provider t := trace.NewTracerProvider() t.RegisterSpanProcessor(trace.NewBatchSpanProcessor(exporter)) // Or use InstallNewPipeline for a simpler setup // _, err = trace.InstallNewPipeline( // trace.WithBatcher(otlptracegrpc.NewExporter()), // // ... other options // ) // if err != nil { // // handle error // } ``` -------------------------------- ### Start Tracer Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/DataDog/dd-trace-go/v2/ddtrace/tracer/api.txt Initializes the tracer with specified options. This must be called before using other tracer functions. ```go func Start(...StartOption) (error) ``` -------------------------------- ### Get SC_CLK_TCK using go-sysconf Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/tklauser/go-sysconf/README.md This example demonstrates how to retrieve the system's clock tick frequency using the `sysconf.Sysconf` function. Ensure the `github.com/tklauser/go-sysconf` package is imported. ```Go package main import ( "fmt" "github.com/tklauser/go-sysconf" ) func main() { // get clock ticks, this will return the same as C.sysconf(C._SC_CLK_TCK) clktck, err := sysconf.Sysconf(sysconf.SC_CLK_TCK) if err == nil { fmt.Printf("SC_CLK_TCK: %v\n", clktck) } } ``` -------------------------------- ### Check if Started by Explorer Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/inconshreveable/mousetrap/README.md Use this function to determine if the current process was launched by a double-click in Windows Explorer. No setup or imports are required beyond importing the mousetrap package. ```go func StartedByExplorer() (bool) ``` -------------------------------- ### Create OTLP/HTTP Trace Exporter Pipeline Source: https://github.com/kubernetes/dns/blob/master/vendor/go.opentelemetry.io/otel/CHANGELOG.md Use `otlptracehttp.NewExportPipeline` to create and install a new OTLP/HTTP trace exporter pipeline. This function simplifies the setup process for HTTP-based OTLP export. ```go import ( "go.opentelemetry.io/otel/sdk/trace" "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp" ) // ... tracerProvider, err := trace.NewExportPipeline( trace.WithBatcher(otlptracehttp.NewExporter()), // ... other options ) if err != nil { // handle error } // Install the tracer provider t := trace.NewTracerProvider() t.RegisterSpanProcessor(trace.NewBatchSpanProcessor(exporter)) // Or use InstallNewPipeline for a simpler setup // _, err = trace.InstallNewPipeline( // trace.WithBatcher(otlptracehttp.NewExporter()), // // ... other options // ) // if err != nil { // // handle error // } ``` -------------------------------- ### Create Root Logger (logimpl) Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/go-logr/logr/README.md Demonstrates how to create the root logger using a specific implementation like 'logimpl'. This is typically done early in an application's lifecycle. ```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 Corefile with consolidated error logging Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/coredns/coredns/plugin/errors/README.md This Corefile configuration uses the 'forward' plugin to resolve queries and configures the 'errors' plugin to consolidate specific error messages. Errors with the suffix ' i/o timeout' are logged as warnings every 5 minutes, and errors starting with 'Failed to ' are logged as errors every 30 seconds. ```corefile . { forward . 8.8.8.8 errors { consolidate 5m ".* i/o timeout$" warning consolidate 30s "^Failed to .+" } } ``` -------------------------------- ### Install uuid Package Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/google/uuid/README.md Use this command to install the uuid package. Ensure you have Go installed and configured. ```sh go get github.com/google/uuid ``` -------------------------------- ### Create and follow a file with tail Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/nxadm/tail/README.md Use this to create a tail instance for a file and follow its content in real-time. Ensure the file path is correct and the program has read permissions. ```Go // Create a tail t, err := tail.TailFile( "/var/log/nginx.log", tail.Config{Follow: true, ReOpen: true}) if err != nil { panic(err) } // Print the text of each received line for line := range t.Lines { fmt.Println(line.Text) } ``` -------------------------------- ### Instantiation with Options Source: https://github.com/kubernetes/dns/blob/master/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Demonstrates how to instantiate a type `T` using a variadic `Option` parameter. This allows for flexible configuration during object creation. ```go func NewT(options ...Option) T {…} ``` -------------------------------- ### Install nxadm/tail library Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/nxadm/tail/README.md Use this command to install the nxadm/tail library and its dependencies. ```Shell go get github.com/nxadm/tail/... ``` -------------------------------- ### Install mapstructure Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/go-viper/mapstructure/v2/README.md Use this command to install the mapstructure library using Go modules. ```shell go get github.com/go-viper/mapstructure/v2 ``` -------------------------------- ### Install httpforwarded with Testing Dependencies Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/theckman/httpforwarded/README.md Install the httpforwarded package along with its testing dependencies for development purposes. ```bash go get -t -u github.com/theckman/httpforwarded ``` -------------------------------- ### Create and Use fsnotify Watcher in Go Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/fsnotify/fsnotify/README.md This example demonstrates how to create a new fsnotify watcher, set up goroutines to listen for events and errors, add a directory to watch, and handle file write events. Ensure the watcher's channels are processed in a goroutine to avoid blocking. ```go package main import ( "log" "github.com/fsnotify/fsnotify" ) func main() { // Create new watcher. watcher, err := fsnotify.NewWatcher() if err != nil { log.Fatal(err) } defer watcher.Close() // Start listening for events. go func() { for { select { case event, ok := <-watcher.Events: if !ok { return } log.Println("event:", event) if event.Has(fsnotify.Write) { log.Println("modified file:", event.Name) } case err, ok := <-watcher.Errors: if !ok { return } log.Println("error:", err) } } }() // Add a path. err = watcher.Add("/tmp") if err != nil { log.Fatal(err) } // Block main goroutine forever. <-make(chan struct{}) } ``` -------------------------------- ### Call C function 'puts' from Go using Purego Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/ebitengine/purego/README.md Demonstrates how to dynamically load a C library (like libSystem on macOS or libc.so.6 on Linux) and call a function (puts) from Go using purego. Ensure CGO_ENABLED is set to 0 when running this example. ```go package main import ( "fmt" runtime "runtime" "github.com/ebitengine/purego" ) func getSystemLibrary() string { switch runtime.GOOS { case "darwin": return "/usr/lib/libSystem.B.dylib" case "linux": return "libc.so.6" default: panic(fmt.Errorf("GOOS=%s is not supported", runtime.GOOS)) } } func main() { libc, err := purego.Dlopen(getSystemLibrary(), purego.RTLD_NOW|purego.RTLD_GLOBAL) if err != nil { panic(err) } var puts func(string) purego.RegisterLibFunc(&puts, libc, "puts") puts("Calling C from Go without Cgo!") } ``` -------------------------------- ### Create and Use S2 Dictionary with Sample Data Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/klauspost/compress/s2/README.md Demonstrates how to create an S2 dictionary from a sample file and use it for encoding and decoding. Ensure the same dictionary is used for both operations. The dictionary can be saved and reloaded. ```Go // Read a sample sample, err := os.ReadFile("sample.json") // Create a dictionary. dict := s2.MakeDict(sample, nil) // b := dict.Bytes() will provide a dictionary that can be saved // and reloaded with s2.NewDict(b). // To encode: encoded := dict.Encode(nil, file) // To decode: decoded, err := dict.Decode(nil, file) ``` -------------------------------- ### Example JSON data Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/go-viper/mapstructure/v2/README.md This is an example of JSON data that might require dynamic decoding into Go structures. ```json { "type": "person", "name": "Mitchell" } ``` -------------------------------- ### Example Encoding and Decoding Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/klauspost/compress/s2/README.md Demonstrates the encoding and decoding process with a sample dictionary and encoded data. Shows how LIT, REPEAT, and MATCH operations are used. ```text Dictionary: `[0x0a][Yesterday 25 bananas were added to Benjamins brown bag]`. Initial repeat offset is set at 10, which is the letter `2`. Encoded `[LIT "10"][REPEAT len=10][LIT "hich"][MATCH off=50 len=6][MATCH off=31 len=6][MATCH off=61 len=10]` Decoded: `[10][ bananas w][hich][ were ][brown ][were added]` Output: `10 bananas which were brown were added` ``` -------------------------------- ### Set start time for last-value aggregates Source: https://github.com/kubernetes/dns/blob/master/vendor/go.opentelemetry.io/otel/CHANGELOG.md The start time for last-value aggregates is now set in the metric SDK. ```go go.opentelemetry.io/otel/sdk/metric ``` -------------------------------- ### Basic etcd Client Usage in Go Source: https://github.com/kubernetes/dns/blob/master/vendor/go.etcd.io/etcd/client/v2/README.md Demonstrates setting and getting a key-value pair using the etcd Go client. Ensure etcd is running and accessible at the specified endpoint. The code configures client connection, creates a keys API, sets a key, and then retrieves it. ```go package main import ( "log" "time" "context" "go.etcd.io/etcd/v3/client" ) func main() { cfg := client.Config{ Endpoints: []string{"http://127.0.0.1:2379"}, Transport: client.DefaultTransport, // set timeout per request to fail fast when the target endpoint is unavailable HeaderTimeoutPerRequest: time.Second, } c, err := client.New(cfg) if err != nil { log.Fatal(err) } kapi := client.NewKeysAPI(c) // set "/foo" key with "bar" value log.Print("Setting '/foo' key with 'bar' value") resp, err := kapi.Set(context.Background(), "/foo", "bar", nil) if err != nil { log.Fatal(err) } else { // print common key info log.Printf("Set is done. Metadata is %q\n", resp) } // get "/foo" key's value log.Print("Getting '/foo' key value") resp, err = kapi.Get(context.Background(), "/foo", nil) if err != nil { log.Fatal(err) } else { // print common key info log.Printf("Get is done. Metadata is %q\n", resp) // print value log.Printf("%q key has %q value\n", resp.Node.Key, resp.Node.Value) } } ``` -------------------------------- ### StartSpanConfig Structure Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/DataDog/dd-trace-go/v2/ddtrace/tracer/api.txt Defines the configuration options for starting a span, including context, parent span, start time, and tags. ```go type StartSpanConfig struct { Context context.Context Parent *SpanContext SpanID uint64 SpanLinks []SpanLink StartTime time.Time Tags map[string]interface{} } ``` -------------------------------- ### Build All Files (Old System) Source: https://github.com/kubernetes/dns/blob/master/vendor/golang.org/x/sys/unix/README.md Use this script to generate Go files for your current OS and architecture with the old build system. Ensure GOOS and GOARCH are set correctly. Requires bash and go. ```bash mkall.sh ``` -------------------------------- ### Update otel-collector example to use Docker Compose Source: https://github.com/kubernetes/dns/blob/master/vendor/go.opentelemetry.io/otel/CHANGELOG.md The otel-collector example now uses Docker Compose for service orchestration instead of Kubernetes. ```go go.opentelemetry.io/otel/example/otel-collector ``` -------------------------------- ### Start Span with Tracer Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/DataDog/dd-trace-go/v2/ddtrace/tracer/api.txt Starts a new span with a given operation name and optional configuration. This is the primary way to create spans. ```go func StartSpan(string, ...StartSpanOption) (*Span) ``` -------------------------------- ### CoreDNS PTR Response Value Rewrite Example Source: https://github.com/kubernetes/dns/blob/master/vendor/github.com/coredns/coredns/plugin/rewrite/README.md Example of rewriting the VALUE part of a DNS response for PTR records using CoreDNS. ```coredns rewrite stop { name suffix .arpa .arpa answer name auto answer value (.*)\.service\.consul\. {1}.coredns.rocks. } ```