### Install and Test Go OLE Source: https://github.com/centaurusinfra/fornax/blob/main/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 interaction. This involves using `go get` to download the package, navigating to the project directory, running tests, and then executing an example script. ```Go 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 ``` -------------------------------- ### Installation Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/github.com/imdario/mergo/README.md Instructions on how to install the Mergo library using go get. ```APIDOC ## Installation go get github.com/imdario/mergo // use in your .go code import ( "github.com/imdario/mergo" ) ``` -------------------------------- ### Install etcd/clientv3 Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/go.etcd.io/etcd/clientv3/README.md Instructions on how to install the etcd/clientv3 Go package using the go get command. ```APIDOC ## Install etcd/clientv3 ### Description Instructions on how to install the etcd/clientv3 Go package using the go get command. ### Method `go get` ### Endpoint N/A ### Parameters N/A ### Request Example ```bash go get go.etcd.io/etcd/clientv3 ``` ### Response N/A ``` -------------------------------- ### Install and Import Afero Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/github.com/spf13/afero/README.md Instructions for installing the Afero library via go get and importing it into a Go project. ```bash go get github.com/spf13/afero ``` ```go import "github.com/spf13/afero" ``` -------------------------------- ### Create Basic HTTP Server in Go using Mux Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/github.com/gorilla/mux/README.md Provides a complete, runnable example of a small HTTP server built with the Gorilla Mux router in Go. This example demonstrates how to define routes and associate them with handler functions, and then start the server to listen on a specified port. It includes necessary imports for HTTP, logging, and the Mux router. ```go package main import ( "net/http" "log" "github.com/gorilla/mux" ) func YourHandler(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Gorilla!\n")) } func main() { r := mux.NewRouter() // Routes consist of a path and a handler function. r.HandleFunc("/", YourHandler) // Bind to a port and pass our router in log.Fatal(http.ListenAndServe(":8000", r)) } ``` -------------------------------- ### Install gRPC-Go Package Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/google.golang.org/grpc/README.md Commands to install the gRPC-Go library using the standard go get tool. ```bash go get -u google.golang.org/grpc ``` -------------------------------- ### Install and Import sigs.k8s.io/yaml Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/sigs.k8s.io/yaml/README.md Instructions for installing the package via go get and importing it into a Go project. ```bash go get sigs.k8s.io/yaml ``` ```go import "sigs.k8s.io/yaml" ``` -------------------------------- ### Install Diskv using Go Get Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/github.com/peterbourgon/diskv/README.md This command installs the Diskv library using the Go package manager. Ensure you have Go 1 installed. ```bash go get github.com/peterbourgon/diskv ``` -------------------------------- ### Install Mergo Go Library Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/github.com/imdario/mergo/README.md Instructions for installing the Mergo Go library using the go get command. This is a prerequisite for using Mergo in your Go projects. ```bash go get github.com/imdario/mergo ``` -------------------------------- ### Install Mint Package Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/github.com/bifurcation/mint/README.md This command installs the Mint package, which is a minimal TLS 1.3 stack for Go. It's the standard way to get any Go package. ```bash go get github.com/bifurcation/mint ``` -------------------------------- ### Automated Kubernetes Setup Scripts Source: https://github.com/centaurusinfra/fornax/wiki/Building-K8s-from-Source Provides optional scripts for automating the Kubernetes build and setup process. These scripts guide through different stages of the setup, potentially requiring reboots between stages. ```bash git clone https://github.com/kxu1985/k8s-build-from-source.git sh k8s-build-from-source/setup_1.sh sh k8s-build-from-source/setup_2.sh sh k8s-build-from-source/setup_3.sh ``` -------------------------------- ### Install Cobra Library Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/github.com/spf13/cobra/README.md Use the go get command to install the Cobra generator and its dependencies into your Go environment. ```shell go get -u github.com/spf13/cobra/cobra ``` -------------------------------- ### Install go-isatty Package Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/README.md This command shows how to install the go-isatty library using the Go build tools. This is a prerequisite for using the library in your Go projects. ```bash go get github.com/mattn/go-isatty ``` -------------------------------- ### Install etcd/clientv3 dependency Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/go.etcd.io/etcd/clientv3/README.md Command to install the official etcd v3 Go client using the go get tool. ```bash go get go.etcd.io/etcd/clientv3 ``` -------------------------------- ### Install json-iterator/go using go get Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/github.com/json-iterator/go/README.md This command demonstrates the standard method for installing the json-iterator/go library using the Go module system. It fetches the latest stable version of the library for use in your Go projects. ```bash go get github.com/json-iterator/go ``` -------------------------------- ### Setup and Contribution Workflow Commands Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/gopkg.in/fsnotify.v1/CONTRIBUTING.md Common command-line operations for installing the package, managing git branches, and executing the test suite across different environments. ```bash go get -u github.com/fsnotify/fsnotify git checkout -b my-new-feature git commit -am 'Add some feature' git remote add fork git@github.com:mycompany/repo.git git push fork my-new-feature ``` ```bash vagrant up vagrant up linux vagrant up bsd vagrant ssh linux -c 'cd fsnotify/fsnotify; go test' ``` -------------------------------- ### Install OpenCensus Go Library Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/go.opencensus.io/README.md Command to install the OpenCensus Go library using the go get command. It is recommended to use vendoring or a dependency management tool. ```bash go get -u go.opencensus.io ``` -------------------------------- ### SpdyStream Server Example in Go Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/github.com/docker/spdystream/README.md This Go code sets up a SpdyStream server that listens for incoming TCP connections on localhost:8080. Upon accepting a connection, it creates a new SpdyStream connection and starts serving streams using the MirrorStreamHandler, which echoes received data. ```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) } } ``` -------------------------------- ### Install Go Tail Package Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/github.com/hpcloud/tail/README.md This command shows how to install the Go 'tail' package and its dependencies using the Go build tools. It fetches the package from its remote repository. ```Shell go get github.com/hpcloud/tail/... ``` -------------------------------- ### Start a Single-Node Raft Cluster Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/go.etcd.io/etcd/raft/README.md Illustrates the process of starting a single-node Raft cluster. The configuration is similar to a multi-node setup, but the peer list is set to include only the current node's ID, 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) ``` -------------------------------- ### Start a Three-Node Raft Cluster Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/go.etcd.io/etcd/raft/README.md Demonstrates how to initialize and start a three-node Raft cluster. This involves creating a memory storage, configuring the node with essential parameters like ID, election/heartbeat ticks, and storage, and then starting the node with peer information for the other two nodes. ```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}}) ``` -------------------------------- ### YAML Package Installation Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/gopkg.in/yaml.v2/README.md Instructions on how to install the yaml package for Go projects. ```APIDOC ## Installation The import path for the package is *gopkg.in/yaml.v2`. To install it, run: ```bash go get gopkg.in/yaml.v2 ``` ``` -------------------------------- ### Install Gorilla Mux Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/github.com/gorilla/mux/README.md This snippet shows how to install the gorilla/mux package using the Go toolchain. Ensure your Go environment is correctly configured before running this command. ```sh go get -u github.com/gorilla/mux ``` -------------------------------- ### Start KubeEdge Cloudcore Source: https://github.com/centaurusinfra/fornax/blob/main/docs/fornax_test/830_release_testplan.md Starts the KubeEdge cloudcore service on the root operator machine. This is a prerequisite for registering edge clusters. ```bash _output/local/bin/cloudcore ``` -------------------------------- ### Install go-colorable Package Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable/README.md This command installs the go-colorable package using the Go build tool. 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 MQTT Go Client Dependencies Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/github.com/eclipse/paho.mqtt.golang/README.md Installs the necessary dependencies for the MQTT Go client, including Google's websockets and proxy packages, using the standard Go toolchain. ```go go get golang.org/x/net/websocket go get golang.org/x/net/proxy ``` -------------------------------- ### Initializing Filesystem Backends Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/github.com/spf13/afero/README.md Examples of initializing native OS and memory-backed filesystems. ```go appfs := afero.NewOsFs() appfs.MkdirAll("src/a", 0755) ``` ```go mm := afero.NewMemMapFs() mm.MkdirAll("src/a", 0755) ``` -------------------------------- ### Generate CloudCore Minimum Configuration Source: https://github.com/centaurusinfra/fornax/blob/main/docs/proposals/configuration.md Generates a minimal configuration file for CloudCore, containing only the essential settings. This is ideal for beginners who need a basic setup to get started with KubeEdge. ```bash # cloudcore --minconfig ``` ```yaml apiVersion: cloudcore.config.kubeedge.io/v1alpha1 kind: CloudCore kubeAPIConfig: kubeConfig: /root/.kube/config master: "" modules: cloudhub: nodeLimit: 10 tlsCAFile: /etc/kubeedge/ca/rootCA.crt tlsCertFile: /etc/kubeedge/certs/edge.crt tlsPrivateKeyFile: /etc/kubeedge/certs/edge.key unixsocket: address: unix:///var/lib/kubeedge/kubeedge.sock enable: true websocket: address: 0.0.0.0 enable: true port: 10000 ``` -------------------------------- ### Initialize QUIC Server in Go Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/github.com/lucas-clemente/quic-go/README.md Demonstrates how to start a QUIC server using the h2quic package. It mirrors the standard library's http.ListenAndServe pattern by specifying the address and certificate paths. ```go http.Handle("/", http.FileServer(http.Dir(wwwDir))) h2quic.ListenAndServeQUIC("localhost:4242", "/path/to/cert/chain.pem", "/path/to/privkey.pem", nil) ``` -------------------------------- ### Go ZFS Filesystem and Snapshot Management Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/github.com/mistifyio/go-zfs/README.md Demonstrates the creation of a ZFS filesystem, taking a snapshot of it, cloning the snapshot, and then destroying the created entities. This example assumes a pre-existing ZFS pool named 'test' and omits error handling for brevity. ```go //assuming a zpool named test //error handling omitted f, err := zfs.CreateFilesystem("test/snapshot-test", nil) ok(t, err) s, err := f.Snapshot("test", nil) ok(t, err) // snapshot is named "test/snapshot-test@test" c, err := s.Clone("test/clone-test", nil) err := c.Destroy() err := s.Destroy() err := f.Destroy() ``` -------------------------------- ### Declare Afero Filesystem Backend Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/github.com/spf13/afero/README.md Demonstrates how to initialize a filesystem backend using either an in-memory map or the standard OS filesystem. ```go var AppFs = afero.NewMemMapFs() // or var AppFs = afero.NewOsFs() ``` -------------------------------- ### Configure and Create a Container Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/github.com/opencontainers/runc/libcontainer/README.md Defines the container configuration including mounts, ID mappings, and resource limits, then initializes the container using a factory. ```go config := &configs.Config{ Parent: "system", Resources: &configs.Resources{ MemorySwappiness: nil, Devices: specconv.AllowedDevices, }, MaskPaths: []string{"/proc/kcore", "/sys/firmware"}, ReadonlyPaths: []string{"/proc/sys", "/proc/sysrq-trigger", "/proc/irq", "/proc/bus"}, Devices: specconv.AllowedDevices, Hostname: "testing", Mounts: []*configs.Mount{ /* ... mount definitions ... */ }, UidMappings: []configs.IDMap{{ContainerID: 0, HostID: 1000, Size: 65536}}, GidMappings: []configs.IDMap{{ContainerID: 0, HostID: 1000, Size: 65536}}, Networks: []*configs.Network{{Type: "loopback", Address: "127.0.0.1/0", Gateway: "localhost"}}, Rlimits: []configs.Rlimit{{Type: unix.RLIMIT_NOFILE, Hard: uint64(1025), Soft: uint64(1025)}}, } container, err := factory.Create("container-id", config) ``` -------------------------------- ### keadm init Source: https://github.com/centaurusinfra/fornax/blob/main/docs/proposals/keadm-scope.md Bootstraps the KubeEdge cloud component, including checking and installing necessary pre-requisites. ```APIDOC ## keadm init ### Description Bootstraps KubeEdge's cloud component. It checks for installed pre-requisites and handles the download, installation, and execution if they are missing. ### Method CLI Command ### Parameters #### Flags - **--docker-version** (string) - Optional - Version of Docker to install (default "18.06.0") - **--kubeedge-version** (string) - Optional - Version of KubeEdge to install (default "0.3.0-beta.0") - **--kubernetes-version** (string) - Optional - Version of Kubernetes to install (default "1.14.1") ### Request Example keadm init --kubeedge-version=0.3.0-beta.0 ``` -------------------------------- ### Interact with CRIU RPC using Go Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/github.com/checkpoint-restore/go-criu/v4/README.md Demonstrates how to initialize the CRIU client and perform basic operations such as retrieving the CRIU version or verifying the installed version against a minimum requirement. ```go c := criu.MakeCriu() version, err := c.GetCriuVersion() fmt.Println(version) // Check if at least a certain CRIU version is installed result, err := c.IsCriuAtLeast(31100) ``` -------------------------------- ### Install and Test netns Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/github.com/vishvananda/netns/README.md Commands to install the netns package via go get and execute tests requiring root privileges. ```bash go get github.com/vishvananda/netns sudo -E go test github.com/vishvananda/netns ``` -------------------------------- ### Setup NSS for Interoperability Testing Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/github.com/bifurcation/mint/README.md These bash commands outline the setup process for the NSS (Network Security Services) library, a prerequisite for interoperability testing with Mint. It involves cloning repositories, setting environment variables, and building NSS. ```bash # Install mint go get github.com/bifurcation/mint # Environment for NSS (you'll probably want a new directory) NSS_ROOT= mkdir $NSS_ROOT cd $NSS_ROOT export USE_64=1 export ENABLE_TLS_1_3=1 export HOST=localhost export DOMSUF=localhost # Build NSS hg clone https://hg.mozilla.org/projects/nss hg clone https://hg.mozilla.org/projects/nspr cd nss make nss_build_all export PLATFORM=`cat $NSS_ROOT/dist/latest` export DYLD_LIBRARY_PATH=$NSS_ROOT/dist/$PLATFORM/lib export LD_LIBRARY_PATH=$NSS_ROOT/dist/$PLATFORM/lib ``` -------------------------------- ### SpdyStream Client Example in Go Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/github.com/docker/spdystream/README.md This Go code demonstrates how to establish a SpdyStream connection to a mirroring server, create a new stream, write data to it, read data back, and then close the stream. It 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() } ``` -------------------------------- ### Basic Version Comparison Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/github.com/blang/semver/README.md Demonstrates how to initialize version objects and perform a basic comparison between two semantic versions. ```go import github.com/blang/semver v1, err := semver.Make("1.0.0-beta") v2, err := semver.Make("2.0.0-beta") v1.Compare(v2) ``` -------------------------------- ### Install aec Go Package Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/github.com/morikuni/aec/README.md This snippet shows how to install the aec Go package using the go get command. It's a prerequisite for using the library in your Go projects. ```bash go get github.com/morikuni/aec ``` -------------------------------- ### Migrate Format-String Logging to Structured Logging Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/github.com/go-logr/logr/README.md Examples showing how to convert traditional format-string log calls into structured key-value pairs. This improves log searchability and consistency across the codebase. ```go // Legacy format-string style klog.V(4).Infof("Client is returning errors: code %v, error %v", responseCode, err); // Structured logging equivalent logger.Error(err, "client returned an error", "code", responseCode); // Legacy format-string style klog.V(4).Infof("Got a Retry-After %ds response for attempt %d to %v", seconds, retries, url); // Structured logging equivalent logger.V(4).Info("got a retry-after response when requesting url", "attempt", retries, "after seconds", seconds, "url", url); ``` -------------------------------- ### Configuring Filtering Backends Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/github.com/spf13/afero/README.md Demonstrates how to wrap existing filesystems with BasePathFs for path restriction or ReadOnlyFs for immutable access. ```go bp := afero.NewBasePathFs(afero.NewOsFs(), "/base/path") ``` ```go fs := afero.NewReadOnlyFs(afero.NewOsFs()) _, err := fs.Create("/file.txt") ``` -------------------------------- ### Install Semver Dependency Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/github.com/blang/semver/README.md Use the go get command to add the semver library to your Go project dependencies. ```bash go get github.com/blang/semver ``` -------------------------------- ### Initialize and Populate LRU Cache in Go Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/github.com/hashicorp/golang-lru/README.md Demonstrates how to instantiate a new LRU cache with a fixed capacity and add items to it. It also shows how to verify the cache size after exceeding the capacity. ```go l, _ := New(128) for i := 0; i < 256; i++ { l.Add(i, nil) } if l.Len() != 128 { panic(fmt.Sprintf("bad len: %v", l.Len())) } ``` -------------------------------- ### Initialize Block Device Filesystem Access Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/github.com/prometheus/procfs/README.md Shows how to initialize a block device filesystem instance that requires access to both /proc and /sys paths. ```go fs, err := blockdevice.NewFS("/proc", "/sys") stats, err := fs.ProcDiskstats() ``` -------------------------------- ### Static Provisioning: Pod Binding PersistentVolumeClaim Example (YAML) Source: https://github.com/centaurusinfra/fornax/blob/main/docs/proposals/csi.md Configures a Pod to use a PersistentVolumeClaim. This YAML defines a Pod that mounts a volume named 'my-csi-volume' which is linked to the 'csi-nfs-pvc'. The volume will be attached and mounted before the pod starts. ```yaml kind: Pod apiVersion: v1 metadata: name: my-csi-app spec: containers: - name: my-frontend image: busybox volumeMounts: - mountPath: "/data" name: my-csi-volume command: [ "sleep", "1000000" ] volumes: - name: my-csi-volume persistentVolumeClaim: claimName: csi-nfs-pvc ``` -------------------------------- ### Initialize Environment and Clone Repository Source: https://github.com/centaurusinfra/fornax/blob/main/scripts/README.md Commands to switch to root, sync SSH keys, and clone the Fornax repository into the appropriate directory structure. ```bash sudo su cat /home/ubuntu/.ssh/authorized_keys > /root/.ssh/authorized_keys mkdir -p /root/go/src/github.com cd /root/go/src/github.com git clone https://github.com/click2cloud-alpha-p/fornax.git ``` -------------------------------- ### Dynamic Provisioning: Pod Binding PersistentVolumeClaim Example (YAML) Source: https://github.com/centaurusinfra/fornax/blob/main/docs/proposals/csi.md Configures a Pod to use a dynamically provisioned PersistentVolumeClaim. This YAML defines a Pod that mounts a volume named 'my-csi-volume' which is linked to the 'csi-hostpath-pvc'. The volume will be provisioned, attached, and mounted before the pod starts. ```yaml kind: Pod apiVersion: v1 metadata: name: my-csi-app spec: containers: - name: my-frontend image: busybox volumeMounts: - mountPath: "/data" name: my-csi-volume command: [ "sleep", "1000000" ] volumes: - name: my-csi-volume persistentVolumeClaim: claimName: csi-hostpath-pvc ``` -------------------------------- ### Initialize Procfs and Retrieve Statistics Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/github.com/prometheus/procfs/README.md Demonstrates how to initialize the proc filesystem mount point using the FS type and retrieve system statistics. ```go fs, err := procfs.NewFS("/proc") stats, err := fs.Stat() ``` -------------------------------- ### Implement CORS Method Middleware in Go Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/github.com/gorilla/mux/README.md This Go code snippet demonstrates how to use the CORSMethodMiddleware from the gorilla/mux router to automatically set the Access-Control-Allow-Methods header. It requires a custom handler to set other CORS headers and an OPTIONS method matcher for the middleware to function correctly. The example sets up a basic HTTP server that handles GET, PUT, PATCH, and OPTIONS requests on the /foo endpoint. ```Go package main import ( "net/http" "github.com/gorilla/mux" ) func main() { r := mux.NewRouter() // IMPORTANT: you must specify an OPTIONS method matcher for the middleware to set CORS headers r.HandleFunc("/foo", fooHandler).Methods(http.MethodGet, http.MethodPut, http.MethodPatch, http.MethodOptions) r.Use(mux.CORSMethodMiddleware(r)) http.ListenAndServe(":8080", r) } func fooHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") if r.Method == http.MethodOptions { return } w.Write([]byte("foo")) } ``` -------------------------------- ### Example: Merging Structs Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/github.com/imdario/mergo/README.md A practical example demonstrating how Mergo.Merge works with structs. ```APIDOC ### Nice example ```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} } ``` ``` -------------------------------- ### Authentication Middleware Example Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/github.com/gorilla/mux/README.md Provides an example of an authentication middleware that checks for a session token. ```APIDOC ## Authentication Middleware Example ### Description This example shows a more complex authentication middleware that checks for a session token in the request headers and maps it to a user. If the token is invalid, it returns a forbidden error. ### Method N/A (Code examples demonstrate Go code) ### Endpoint N/A ### Parameters N/A ### Request Body N/A ### Request Example ```go // Define our struct type authenticationMiddleware struct { tokenUsers map[string]string } // Initialize it somewhere func (amw *authenticationMiddleware) Populate() { amw.tokenUsers["00000000"] = "user0" amw.tokenUsers["aaaaaaaa"] = "userA" amw.tokenUsers["05f717e5"] = "randomUser" amw.tokenUsers["deadbeef"] = "user0" } // Middleware function func (amw *authenticationMiddleware) Middleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { token := r.Header.Get("X-Session-Token") if user, found := amw.tokenUsers[token]; found { // We found the token in our map log.Printf("Authenticated user %s\n", user) // Pass down the request to the next middleware (or final handler) next.ServeHTTP(w, r) } else { // Write an error and stop the handler chain http.Error(w, "Forbidden", http.StatusForbidden) } }) } r := mux.NewRouter() r.HandleFunc("/", handler) amw := authenticationMiddleware{} amw.Populate() r.Use(amw.Middleware) ``` ### Response N/A ### Response Example N/A ``` -------------------------------- ### Initialize etcd client Source: https://github.com/centaurusinfra/fornax/blob/main/vendor/go.etcd.io/etcd/clientv3/README.md Demonstrates how to create a new etcd client instance with specified endpoints and a dial timeout. It is important to defer the closing of the client to prevent resource leaks. ```go cli, err := clientv3.New(clientv3.Config{ Endpoints: []string{"localhost:2379", "localhost:22379", "localhost:32379"}, DialTimeout: 5 * time.Second, }) if err != nil { // handle error! } defer cli.Close() ```