### Installing Go-Autorest Dependencies Source: https://github.com/openkruise/controllermesh/blob/master/vendor/github.com/Azure/go-autorest/README.md Provides the go get commands to install the necessary packages from the go-autorest library, including autorest, azure, date, and to subpackages. ```bash go get github.com/Azure/go-autorest/autorest go get github.com/Azure/go-autorest/autorest/azure go get github.com/Azure/go-autorest/autorest/date go get github.com/Azure/go-autorest/autorest/to ``` -------------------------------- ### Install jsonpatch Library (Go) Source: https://github.com/openkruise/controllermesh/blob/master/vendor/github.com/evanphx/json-patch/README.md Instructions for installing the jsonpatch library using go get. Supports latest and stable versions. ```bash go get -u github.com/evanphx/json-patch/v5 go get -u gopkg.in/evanphx/json-patch.v5 go get -u gopkg.in/evanphx/json-patch.v4 ``` -------------------------------- ### Install Etcd Client v3 Go Package Source: https://github.com/openkruise/controllermesh/blob/master/vendor/go.etcd.io/etcd/clientv3/README.md Installs the official Go etcd client v3 using the go get command. This is the first step to using the client in a Go project. ```bash go get go.etcd.io/etcd/clientv3 ``` -------------------------------- ### Install Ginkgo CLI Globally Source: https://github.com/openkruise/controllermesh/blob/master/vendor/github.com/onsi/ginkgo/README.md Installs the Ginkgo command line interface globally using the go get command. Ensure the GOBIN directory is in your system's PATH for the command to be accessible. Refer to 'go help install' for more details. ```bash go get -u github.com/onsi/ginkgo/ginkgo ``` -------------------------------- ### Install Mergo Go Package Source: https://github.com/openkruise/controllermesh/blob/master/vendor/github.com/imdario/mergo/README.md Instructions on how to install the Mergo library using the Go build tool. This is a prerequisite for using Mergo in your Go projects. ```go go get github.com/imdario/mergo ``` -------------------------------- ### Installation of go-colorable Source: https://github.com/openkruise/controllermesh/blob/master/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable/README.md This command installs the go-colorable package using the Go module system. It fetches the package and its dependencies, making it available for use in your Go projects. ```bash go get github.com/mattn/go-colorable ``` -------------------------------- ### Install go.uber.org/atomic package Source: https://github.com/openkruise/controllermesh/blob/master/vendor/go.uber.org/atomic/README.md This snippet shows how to install the go.uber.org/atomic package using the go get command. It specifies version 1 of the package. ```shell go get -u go.uber.org/atomic@v1 ``` -------------------------------- ### Coexisting with glog in Go Source: https://github.com/openkruise/controllermesh/blob/master/vendor/k8s.io/klog/v2/README.md This example shows how to integrate klog/v2 alongside glog in the same project. It covers initializing and synchronizing flags from the global `flag.CommandLine` FlagSet and using `alsologtostderr` for combined stderr output. ```go import ( "flag" "k8s.io/klog/v2" "github.com/golang/glog" ) func main() { // Initialize flags for both klog and glog klog.InitFlags(nil) // Ensure glog flags are also parsed if they exist flag.Parse() // Set alsologtostderr to true for combined output flag.Set("alsologtostderr", "true") klog.Info("klog message") glog.Info("glog message") } ``` -------------------------------- ### Install json-iterator/go using go get Source: https://github.com/openkruise/controllermesh/blob/master/vendor/github.com/json-iterator/go/README.md This command installs the json-iterator/go library using the Go modules system. Ensure you have a Go development environment set up. ```bash go get github.com/json-iterator/go ``` -------------------------------- ### Install Golang Semver Library Source: https://github.com/openkruise/controllermesh/blob/master/vendor/github.com/blang/semver/README.md Installs the semver library for Go projects. It is recommended to vendor dependencies or use specific version tags. ```bash go get github.com/blang/semver ``` -------------------------------- ### Raft State Machine Handling Loop Example Source: https://github.com/openkruise/controllermesh/blob/master/vendor/go.etcd.io/etcd/raft/README.md An example of the main state machine handling loop for a Raft node. It demonstrates processing ticks, handling ready updates (saving state, sending messages, applying entries), and advancing the node. ```go for { select { case <-s.Ticker: n.Tick() case rd := <-s.Node.Ready(): saveToStorage(rd.HardState, rd.Entries, rd.Snapshot) send(rd.Messages) if !raft.IsEmptySnap(rd.Snapshot) { processSnapshot(rd.Snapshot) } for _, entry := range rd.CommittedEntries { process(entry) if entry.Type == raftpb.EntryConfChange { var cc raftpb.ConfChange cc.Unmarshal(entry.Data) ``` -------------------------------- ### Install Azure AD Authentication Package for Go Source: https://github.com/openkruise/controllermesh/blob/master/vendor/github.com/Azure/go-autorest/autorest/adal/README.md Installs the `adal` package, a Go library for Azure Active Directory authentication. This command uses the Go build tool to fetch and install the specified package and its dependencies. ```bash go get -u github.com/Azure/go-autorest/autorest/adal ``` -------------------------------- ### Mergo Example: Merging Structs Source: https://github.com/openkruise/controllermesh/blob/master/vendor/github.com/imdario/mergo/README.md A complete runnable example demonstrating Mergo's struct merging capabilities. It defines two `Foo` structs, merges the source into the destination, and prints the result, showing how exported fields are updated. ```go package main import ( "fmt" "github.com/imdario/mergo" ) type Foo struct { A string B int64 } func main() { src := Foo{ A: "one", B: 2, } dest := Foo{ A: "two", } mergo.Merge(&dest, src) fmt.Println(dest) // Will print // {two 2} } ``` -------------------------------- ### Start a Three-Node Raft Cluster Source: https://github.com/openkruise/controllermesh/blob/master/vendor/go.etcd.io/etcd/raft/README.md Initializes and starts a three-node Raft cluster using an in-memory storage. Requires manual startup of each node with peer information. ```go storage := raft.NewMemoryStorage() c := &Config{ ID: 0x01, ElectionTick: 10, HeartbeatTick: 1, Storage: storage, MaxSizePerMsg: 4096, MaxInflightMsgs: 256, } // Set peer list to the other nodes in the cluster. // Note that they need to be started separately as well. n := raft.StartNode(c, []raft.Peer{{ID: 0x02}, {ID: 0x03}}) ``` -------------------------------- ### Define and Configure a RESTful Web Service in Go Source: https://github.com/openkruise/controllermesh/blob/master/vendor/github.com/emicklei/go-restful/README.md This Go code snippet demonstrates how to define a RESTful web service using the go-restful package. It shows setting the service path, supported MIME types for consumption and production, and defining a GET route for retrieving user data with path parameters. This example highlights the fluent API for service configuration and route 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") ... } ``` -------------------------------- ### Install `aefix` Tool for App Engine Package Upgrades Source: https://github.com/openkruise/controllermesh/blob/master/vendor/google.golang.org/appengine/README.md Installs the `aefix` command-line tool, which automates the upgrade of legacy `import "appengine"` packages to the fully qualified `google.golang.org/appengine` paths. ```bash go get google.golang.org/appengine/cmd/aefix ``` -------------------------------- ### Install fsnotify using Go (Go) Source: https://github.com/openkruise/controllermesh/blob/master/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md Installs or updates the fsnotify package from GitHub using the Go command-line tool. This is the recommended way to ensure the original import path is used. ```go go get -u github.com/fsnotify/fsnotify ``` -------------------------------- ### Command Line Tool for Token Acquisition (Shell) Source: https://github.com/openkruise/controllermesh/blob/master/vendor/github.com/Azure/go-autorest/autorest/adal/README.md This example shows the usage and options for the `adal` command-line tool, which simplifies token acquisition for various flows. It supports modes like 'device', 'secret', and 'cert', and accepts parameters such as application ID, tenant ID, resource, and certificate path. The example demonstrates acquiring a token for the Azure Management API using the device code flow. Input is command-line arguments, and the output is an access token or usage information. ```shell adal -h Usage of ./adal: -applicationId string application id -certificatePath string path to pk12/PFC application certificate -mode string authentication mode (device, secret, cert, refresh) (default "device") -resource string resource for which the token is requested -secret string application secret -tenantId string tenant id -tokenCachePath string location of oath token cache (default "/home/cgc/.adal/accessToken.json") ``` ```shell adal -mode device \ -applicationId "APPLICATION_ID" \ -tenantId "TENANT_ID" \ -resource https://management.core.windows.net/ ``` -------------------------------- ### Install gRPC-Go Package Source: https://github.com/openkruise/controllermesh/blob/master/vendor/google.golang.org/grpc/README.md Installs the gRPC-Go library using the Go package manager. This command fetches the latest stable version of the library. For Go 1.11+ with modules, simply importing the package is sufficient. ```bash go get -u google.golang.org/grpc ``` -------------------------------- ### Install YAML Package for Testing Source: https://github.com/openkruise/controllermesh/blob/master/vendor/github.com/imdario/mergo/README.md A note indicating that the `gopkg.in/yaml.v2` package might be required for tests if they are failing due to missing dependencies. This is typically for external integrations or specific testing scenarios. ```go go get gopkg.in/yaml.v2 ``` -------------------------------- ### Initializing klog Flags Explicitly Source: https://github.com/openkruise/controllermesh/blob/master/vendor/k8s.io/klog/v2/README.md This example shows the explicit initialization of global flags for klog using `klog.InitFlags(nil)`. Unlike glog, klog no longer uses the `init()` method for flag registration, requiring manual initialization. ```go import ( "k8s.io/klog/v2" "flag" ) func main() { klog.InitFlags(nil) flag.Parse() // ... rest of your application } ``` -------------------------------- ### Zap SugaredLogger Quick Start Source: https://github.com/openkruise/controllermesh/blob/master/vendor/go.uber.org/zap/README.md Demonstrates how to use Zap's SugaredLogger for logging with both structured and printf-style messages. This logger is suitable for contexts where performance is important but not the absolute critical factor. It includes logging with key-value pairs and formatted strings. ```go logger, _ := zap.NewProduction() defer logger.Sync() // flushes buffer, if any sugar := logger.Sugar() sugar.Infow("failed to fetch URL", // Structured context as loosely typed key-value pairs. "url", url, "attempt", 3, "backoff", time.Second, ) sugar.Infof("Failed to fetch URL: %s", url) ``` -------------------------------- ### Zap Logger Quick Start Source: https://github.com/openkruise/controllermesh/blob/master/vendor/go.uber.org/zap/README.md Illustrates the usage of Zap's core Logger for performance-critical applications requiring type safety. This logger exclusively supports structured logging, offering higher performance and fewer allocations compared to SugaredLogger. ```go logger, _ := zap.NewProduction() deffer logger.Sync() logger.Info("failed to fetch URL", // Structured context as strongly typed Field values. zap.String("url", url), zap.Int("attempt", 3), zap.Duration("backoff", time.Second) ) ``` -------------------------------- ### Bootstrap and Run Ginkgo Tests Source: https://github.com/openkruise/controllermesh/blob/master/vendor/github.com/onsi/ginkgo/README.md Guides through the process of setting up and running tests using Ginkgo. It includes bootstrapping a new test suite, generating a sample test file, writing custom tests, and executing them using either 'go test', 'ginkgo', or 'go run'. ```bash cd path/to/package/you/want/to/test ginkgo bootstrap # set up a new ginkgo suite ginkgo generate # will create a sample test file. edit this file and add your tests then... go test # to run your tests ginkgo # also runs your tests ``` -------------------------------- ### Enable Datastore Key Conversion for Basic/Manual Scaling Source: https://github.com/openkruise/controllermesh/blob/master/vendor/google.golang.org/appengine/README.md Configures the `/_ah/start` handler to enable automatic conversion of datastore keys between `cloud.google.com/go/datastore` and `google.golang.org/appengine/datastore` for basic and manual scaling App Engine environments. ```go http.HandleFunc("/_ah/start", func(w http.ResponseWriter, r *http.Request) { datastore.EnableKeyConversion(appengine.NewContext(r)) }) ``` -------------------------------- ### Prepare, Send, and Respond HTTP Request Pattern in Go Source: https://github.com/openkruise/controllermesh/blob/master/vendor/github.com/Azure/go-autorest/README.md Demonstrates the core pattern for sending HTTP requests using go-autorest. It shows how to prepare a request with authorization, send it with various options like logging and retries, and then respond by handling the response body and closing the connection. Dependencies include 'net/http' and 'time'. ```go req, err := Prepare(&http.Request{}, token.WithAuthorization()) resp, err := Send(req, WithLogging(logger), DoErrorIfStatusCode(http.StatusInternalServerError), DoCloseIfError(), DoRetryForAttempts(5, time.Second)) err = Respond(resp, ByDiscardingBody(), ByClosing()) ``` -------------------------------- ### Install and Import sigs.k8s.io/yaml in Go Source: https://github.com/openkruise/controllermesh/blob/master/vendor/sigs.k8s.io/yaml/README.md This snippet shows how to install the sigs.k8s.io/yaml library using go get and how to import it into your Go project. This is the prerequisite for using the library's functionalities. ```go go get sigs.k8s.io/yaml import "sigs.k8s.io/yaml" ``` -------------------------------- ### Get integer flag value from a FlagSet with pflag Source: https://github.com/openkruise/controllermesh/blob/master/vendor/github.com/spf13/pflag/README.md Helper functions like `GetInt()` are available to retrieve flag values from a `pflag.FlagSet`. This example shows how to get an integer value for a flag named 'flagname'. It's important that the flag exists and is of the expected type, otherwise an error will occur. ```go i, err := flagset.GetInt("flagname") ``` -------------------------------- ### Get/Set Interface{} Value with reflect2 Source: https://github.com/openkruise/controllermesh/blob/master/vendor/github.com/modern-go/reflect2/README.md Demonstrates how to get and set values of an interface{} type using reflect2. It requires the pointer to the type for set operations. The example shows setting a variable `i` to the value of `j`. ```go valType := reflect2.TypeOf(1) i := 1 j := 10 valType.Set(&i, &j) // i will be 10 ``` -------------------------------- ### Parse RSA Public Key from PEM Encoding in Go Source: https://github.com/openkruise/controllermesh/blob/master/vendor/github.com/form3tech-oss/jwt-go/MIGRATION_GUIDE.md Provides an example of how to use `jwt.ParseRSAPublicKeyFromPEM` to parse an RSA public key from PEM encoding. This is a helper function introduced to replace the older behavior of accepting `[]byte` keys directly, which was a security risk. ```go import ( "crypto/rsa" "fmt" "github.com/golang-jwt/jwt/v4" ) // Dummy keyLookup function for demonstration func lookupPublicKey(kid string) ([]byte, error) { // In a real application, you would fetch the public key based on the kid // For this example, we'll return a placeholder PEM encoded key publicKeyPEM := []byte(`-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE...\n-----END PUBLIC KEY-----`) return publicKeyPEM, nil } func getKeyFromPEM(token *jwt.Token) (interface{}, error) { // Validate the signing method if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok { return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) } // Look up the public key using the key ID (kid) keyBytes, err := lookupPublicKey(token.Header["kid"].(string)) if err != nil { return nil, fmt.Errorf("failed to lookup public key: %w", err) } // Parse the PEM encoded public key publicKey, err := jwt.ParseRSAPublicKeyFromPEM(keyBytes) if err != nil { return nil, fmt.Errorf("failed to parse public key from PEM: %w", err) } return publicKey, nil } ``` -------------------------------- ### Apply JSON Patches using CLI Source: https://github.com/openkruise/controllermesh/blob/master/vendor/github.com/evanphx/json-patch/README.md Demonstrates the usage of the `json-patch` command-line tool. This tool allows applying multiple JSON patch documents to a JSON document provided via standard input. The example shows how to install the tool and pipe a document through multiple patch files to achieve a modified output. ```bash $ go install github.com/evanphx/json-patch/cmd/json-patch $ cat document.json | json-patch -p patch.1.json -p patch.2.json {"address":"123 Main St","age":"21","name":"Jane"} ``` -------------------------------- ### SpdyStream Server Example (Go) Source: https://github.com/openkruise/controllermesh/blob/master/vendor/github.com/docker/spdystream/README.md This Go code sets up a mirroring server using SpdyStream without authentication. It listens for incoming TCP connections, establishes a new spdy connection for each, and serves streams using a handler that mirrors the received data. Requires the 'github.com/docker/spdystream' package. ```go package main import ( "github.com/docker/spdystream" "net" ) func main() { listener, err := net.Listen("tcp", "localhost:8080") if err != nil { panic(err) } for { conn, err := listener.Accept() if err != nil { panic(err) } spdyConn, err := spdystream.NewConnection(conn, true) if err != nil { panic(err) } go spdyConn.Serve(spdystream.MirrorStreamHandler) } } ``` -------------------------------- ### Enable Datastore Key Conversion for Automatic Scaling Source: https://github.com/openkruise/controllermesh/blob/master/vendor/google.golang.org/appengine/README.md Demonstrates how to enable datastore key conversion in an automatic scaling App Engine environment, as `/_ah/start` is not supported. This ensures compatibility with `cloud.google.com/go/datastore` by calling `datastore.EnableKeyConversion` before datastore operations. ```go datastore.EnableKeyConversion(appengine.NewContext(r)) ``` -------------------------------- ### Start a Single-Node Raft Cluster Source: https://github.com/openkruise/controllermesh/blob/master/vendor/go.etcd.io/etcd/raft/README.md Starts a single-node Raft cluster where the node is its own peer, enabling it to become the leader. ```go // Create storage and config as shown above. // Set peer list to itself, so this node can become the leader of this single-node cluster. peers := []raft.Peer{{ID: 0x01}} n := raft.StartNode(c, peers) ``` -------------------------------- ### Initialize and Read Proc Filesystem Statistics (Go) Source: https://github.com/openkruise/controllermesh/blob/master/vendor/github.com/prometheus/procfs/README.md This snippet demonstrates how to initialize the proc filesystem mount point and read CPU statistics using the procfs library. It requires the path to the proc filesystem as input. ```Go fs, err := procfs.NewFS("/proc") stats, err := fs.Stat() ``` -------------------------------- ### Install ControllerMesh CRDs (Bash) Source: https://context7.com/openkruise/controllermesh/llms.txt This bash script installs the Custom Resource Definitions (CRDs) required for ControllerMesh. It can be executed using 'make install' or by manually applying the YAML files with kubectl. Ensure kubectl is configured to communicate with your Kubernetes cluster. ```bash # Install ControllerMesh CRDs make install # Or apply manually kubectl apply -f config/crd/bases/ctrlmesh.kruise.io_virtualapps.yaml kubectl apply -f config/crd/bases/ctrlmesh.kruise.io_trafficpolicies.yaml kubectl apply -f config/crd/bases/ctrlmesh.kruise.io_managerstates.yaml ``` -------------------------------- ### Initialize Proxy Sidecar with API Server and Webhook Proxies (Go) Source: https://context7.com/openkruise/controllermesh/llms.txt This Go code initializes the proxy sidecar, starting API server and webhook proxies. It establishes gRPC connections to the manager, verifies environment variables, and configures various proxy options. Dependencies include standard Go libraries and Kubernetes client packages. ```go package main import ( "flag" "math/rand" "net" "os" "time" "github.com/go-logr/glog" "github.com/spf13/pflag" "k8s.io/client-go/rest" "openkruise.io/controllermesh/pkg/apiserverproxy" "openkruise.io/controllermesh/pkg/client" "openkruise.io/controllermesh/pkg/constants" "openkruise.io/controllermesh/pkg/healthz" "openkruise.io/controllermesh/pkg/protomanager" "openkruise.io/controllermesh/pkg/signals" "openkruise.io/controllermesh/pkg/webhookproxy" ) var ( webhookCertDir = flag.String("webhook-cert-dir", "/var/run/secrets/kubernetes.io/serviceaccount/certs", "Directory containing tls certs") webhookServePort = flag.Int("webhook-serve-port", 0, "Webhook server port") proxyWebhookPort = flag.Int("proxy-webhook-port", 10250, "Proxy webhook port") proxyApiserverPort = flag.Int("proxy-apiserver-port", 8080, "Proxy API server port") leaderElectionName = flag.String("leader-election-name", "ctrlmesh-leader-election", "Leader election name") userAgentOverride = flag.String("user-agent-override", "", "User agent override") ) // Placeholder for actual rest config retrieval func getRestConfig() (*rest.Config, error) { // In a real scenario, this would use clientcmd.BuildConfigFromFlags or similar return &rest.Config{}, nil } // Placeholder for actual serveHTTP function func serveHTTP(ctx context.Context, handler *healthz.Handler) { klog.Info("Serving health and metrics") // Implement HTTP serving logic here } func main() { rand.Seed(time.Now().UnixNano()) pflag.CommandLine.AddGoFlagSet(flag.CommandLine) pflag.Parse() // Verify pod identity environment variables if os.Getenv(constants.EnvPodNamespace) == "" || os.Getenv(constants.EnvPodName) == "" { klog.Fatalf("Environment %s and %s must be set", constants.EnvPodNamespace, constants.EnvPodName) } // Initialize Kubernetes client cfg, err := getRestConfig() if err != nil { klog.Fatalf("Failed to get rest config: %v", err) } if err := client.NewRegistry(cfg); err != nil { klog.Fatalf("Failed to new client registry: %v", err) } ctx := signals.SetupSignalHandler() readyHandler := &healthz.Handler{} // Start gRPC client to receive specs from manager proxyClient := protomanager.NewGrpcClient() if err := proxyClient.Start(ctx); err != nil { klog.Fatalf("Failed to start proxy client: %v", err) } // Start webhook proxy if configured var stoppedWebhook <-chan struct{} if *webhookServePort > 0 { opts := &webhookproxy.Options{ CertDir: *webhookCertDir, BindPort: *proxyWebhookPort, WebhookPort: *webhookServePort, SpecManager: proxyClient.GetSpecManager(), } proxy := webhookproxy.NewProxy(opts) readyHandler.Checks["webhookProxy"] = proxy.HealthFunc stoppedWebhook, err = proxy.Start(ctx) if err != nil { klog.Fatalf("Failed to start webhook proxy: %v", err) } } // Start API server proxy opts := apiserverproxy.NewOptions() opts.Config = rest.CopyConfig(cfg) opts.SecureServingOptions.ServerCert.CertKey.KeyFile = "/var/run/secrets/kubernetes.io/serviceaccount/ctrlmesh/tls.key" opts.SecureServingOptions.ServerCert.CertKey.CertFile = "/var/run/secrets/kubernetes.io/serviceaccount/ctrlmesh/tls.crt" opts.SecureServingOptions.BindAddress = net.ParseIP("127.0.0.1") opts.SecureServingOptions.BindPort = *proxyApiserverPort opts.LeaderElectionName = *leaderElectionName opts.UserAgentOverride = *userAgentOverride opts.SpecManager = proxyClient.GetSpecManager() proxy, err := apiserverproxy.NewProxy(opts) if err != nil { klog.Fatalf("Failed to new apiserver proxy: %v", err) } stoppedApiserver, err := proxy.Start(ctx) if err != nil { klog.Fatalf("Failed to start apiserver proxy: %v", err) } // Serve metrics and health endpoints serveHTTP(ctx, readyHandler) <- klog.Infof("Apiserver proxy stopped") } ``` -------------------------------- ### SpdyStream Client Example (Go) Source: https://github.com/openkruise/controllermesh/blob/master/vendor/github.com/docker/spdystream/README.md This Go code demonstrates how to connect to a mirroring server using SpdyStream without authentication. It establishes a connection, creates a new spdy stream, writes data to it, reads data back, and then closes the stream. Requires the 'github.com/docker/spdystream' package. ```go package main import ( "fmt" "github.com/docker/spdystream" "net" "net/http" ) func main() { conn, err := net.Dial("tcp", "localhost:8080") if err != nil { panic(err) } spdyConn, err := spdystream.NewConnection(conn, false) if err != nil { panic(err) } go spdyConn.Serve(spdystream.NoOpStreamHandler) stream, err := spdyConn.CreateStream(http.Header{}, nil, false) if err != nil { panic(err) } stream.Wait() fmt.Fprint(stream, "Writing to stream") buf := make([]byte, 25) stream.Read(buf) fmt.Println(string(buf)) stream.Close() } ``` -------------------------------- ### Authenticate with Client Certificate (Go) Source: https://github.com/openkruise/controllermesh/blob/master/vendor/github.com/Azure/go-autorest/autorest/adal/README.md This Go code snippet demonstrates how to authenticate using a client certificate (PFX file). It reads the certificate file, decodes the PKCS12 data to extract the certificate and private key, and then uses these to create a Service Principal Token. Finally, it refreshes the token to acquire an access token. Dependencies include the 'io/ioutil', 'fmt', and 'adal' packages. Input is a certificate file path, and the output is a Service Principal Token or an error. ```go certificatePath := "./example-app.pfx" certData, err := ioutil.ReadFile(certificatePath) if err != nil { return nil, fmt.Errorf("failed to read the certificate file (%s): %v", certificatePath, err) } // Get the certificate and private key from pfx file certificate, rsaPrivateKey, err := decodePkcs12(certData, "") if err != nil { return nil, fmt.Errorf("failed to decode pkcs12 certificate while creating spt: %v", err) } spt, err := adal.NewServicePrincipalTokenFromCertificate( *oauthConfig, applicationID, certificate, rsaPrivateKey, resource, callbacks...) // Acquire a new access token er P if (err == nil) { token := spt.Token } ``` -------------------------------- ### Semver Parsing, Formatting, and Comparison in Go Source: https://github.com/openkruise/controllermesh/blob/master/vendor/github.com/blang/semver/README.md Provides a comprehensive example of using the semver library in Go. It covers parsing version strings, accessing major, minor, patch, pre-release, and build metadata, performing comparisons, and manipulating versions. Requires the 'github.com/blang/semver' package. ```go import "github.com/blang/semver" import "fmt" v, err := semver.Make("0.0.1-alpha.preview+123.github") fmt.Printf("Major: %d\n", v.Major) fmt.Printf("Minor: %d\n", v.Minor) fmt.Printf("Patch: %d\n", v.Patch) fmt.Printf("Pre: %s\n", v.Pre) fmt.Printf("Build: %s\n", v.Build) // Prerelease versions array if len(v.Pre) > 0 { fmt.Println("Prerelease versions:") for i, pre := range v.Pre { fmt.Printf("%d: %q\n", i, pre) } } // Build meta data array if len(v.Build) > 0 { fmt.Println("Build meta data:") for i, build := range v.Build { fmt.Printf("%d: %q\n", i, build) } } v001, err := semver.Make("0.0.1") // Compare using helpers: v.GT(v2), v.LT, v.GTE, v.LTE v001.GT(v) == true v.LT(v001) == true v.GTE(v) == true v.LTE(v) == true // Or use v.Compare(v2) for comparisons (-1, 0, 1): v001.Compare(v) == 1 v.Compare(v001) == -1 v.Compare(v) == 0 // Manipulate Version in place: v.Pre[0], err = semver.NewPRVersion("beta") if err != nil { fmt.Printf("Error parsing pre release version: %q", err) } fmt.Println("\nValidate versions:") v.Build[0] = "?" err = v.Validate() if err != nil { fmt.Printf("Validation failed: %s\n", err) } ``` -------------------------------- ### Split Trace into Steps in Go Source: https://github.com/openkruise/controllermesh/blob/master/vendor/k8s.io/utils/trace/README.md Illustrates how to divide a trace into multiple sequential steps, logging each step individually. This allows for more granular performance analysis within a single operation. ```go func doSomething() { opTrace := trace.New("operation") defer opTrace.LogIfLong(100 * time.Millisecond) // do step 1 opTrace.Step("step1", Field{Key: "stepFieldKey1", Value: "stepFieldValue1"}) // do step 2 opTrace.Step("step2") } ``` -------------------------------- ### Create and Log Trace in Go Source: https://github.com/openkruise/controllermesh/blob/master/vendor/k8s.io/utils/trace/README.md Demonstrates how to create a new trace with a name and optional fields, and then log it if its execution time exceeds a specified duration. This is useful for monitoring the performance of specific operations. ```go func doSomething() { opTrace := trace.New("operation", Field{Key: "fieldKey1", Value: "fieldValue1"}) defer opTrace.LogIfLong(100 * time.Millisecond) // do something } ``` -------------------------------- ### Start a Raft Node to Join an Existing Cluster Source: https://github.com/openkruise/controllermesh/blob/master/vendor/go.etcd.io/etcd/raft/README.md Starts a Raft node without initial peer information, designed to join an existing cluster. The node should be added to the cluster configuration via `ProposeConfChange` on an existing node. ```go // Create storage and config as shown above. n := raft.StartNode(c, nil) ``` -------------------------------- ### Build sys/unix using mkall.sh (New System) Source: https://github.com/openkruise/controllermesh/blob/master/vendor/golang.org/x/sys/unix/README.md The new build system for GOOS == 'linux' uses a Docker container for reproducible builds. This script requires bash, go, and docker. It generates files for all GOOS/GOARCH pairs supported by the new system from a single amd64/Linux environment. ```bash # Ensure GOOS and GOARCH are set correctly for Linux # Generate all files for all GOOS/GOARCH pairs in the new build system ./mkall.sh # Show the commands that will be run without executing them ./mkall.sh -n ``` -------------------------------- ### Install nxadm/tail Package Source: https://github.com/openkruise/controllermesh/blob/master/vendor/github.com/nxadm/tail/README.md Provides the command to install the `nxadm/tail` Go package and its dependencies using the Go toolchain. This is a prerequisite for using the tailing functionality in Go projects. ```bash go get github.com/nxadm/tail/... ``` -------------------------------- ### Migrate Kubernetes klog to Controller Mesh logger (Go) Source: https://github.com/openkruise/controllermesh/blob/master/vendor/github.com/go-logr/logr/README.md Demonstrates how to convert Kubernetes klog calls using format strings to the Controller Mesh logger's key-value pair approach. This improves log readability and performance by avoiding direct format string usage. ```Go logger.Error(err, "client returned an error", "code", responseCode) // Original klog: klog.V(4).Infof("Client is returning errors: code %v, error %v", responseCode, err) ``` ```Go logger.V(4).Info("got a retry-after response when requesting url", "attempt", retries, "after seconds", seconds, "url", url) // Original klog: klog.V(4).Infof("Got a Retry-After %ds response for attempt %d to %v", seconds, retries, url) ``` ```Go logger.Info("unable to reflect over type", "type", fmt.Sprintf("%T")) // Original klog: log.Printf("unable to reflect over type %T") ```