### Install Nacos-sdk-go Source: https://github.com/nacos-group/nacos-sdk-go/blob/master/README.md Use 'go get' to install the SDK. Ensure your Go version is over 1.15 and Nacos version is over 2.x. ```sh go get -u github.com/nacos-group/nacos-sdk-go/v2 ``` -------------------------------- ### Create Nacos Config Client Source: https://context7.com/nacos-group/nacos-sdk-go/llms.txt Initializes an IConfigClient for configuration operations like get, publish, delete, and listen. Ensure Nacos server is running and accessible. ```go package main import ( "github.com/nacos-group/nacos-sdk-go/v2/clients" "github.com/nacos-group/nacos-sdk-go/v2/clients/config_client" "github.com/nacos-group/nacos-sdk-go/v2/common/constant" "github.com/nacos-group/nacos-sdk-go/v2/vo" ) func newConfigClient() config_client.IConfigClient { cc := *constant.NewClientConfig( constant.WithNamespaceId(""), constant.WithTimeoutMs(5000), constant.WithNotLoadCacheAtStart(true), constant.WithLogDir("/tmp/nacos/log"), constant.WithCacheDir("/tmp/nacos/cache"), constant.WithLogLevel("info"), ) sc := []constant.ServerConfig{ *constant.NewServerConfig("127.0.0.1", 8848, constant.WithContextPath("/nacos")), } client, err := clients.NewConfigClient(vo.NacosClientParam{ ClientConfig: &cc, ServerConfigs: sc, }) if err != nil { panic(err) } return client } ``` -------------------------------- ### clients.NewConfigClient Source: https://context7.com/nacos-group/nacos-sdk-go/llms.txt Creates a new Nacos dynamic configuration client (`IConfigClient`) used for configuration get, publish, delete, and listen operations. ```APIDOC ## clients.NewConfigClient — Create a dynamic-configuration client Returns an `IConfigClient` used for all configuration get/publish/delete/listen operations. ```go package main import ( "github.com/nacos-group/nacos-sdk-go/v2/clients" "github.com/nacos-group/nacos-sdk-go/v2/clients/config_client" "github.com/nacos-group/nacos-sdk-go/v2/common/constant" "github.com/nacos-group/nacos-sdk-go/v2/vo" ) func newConfigClient() config_client.IConfigClient { cc := *constant.NewClientConfig( constant.WithNamespaceId(""), constant.WithTimeoutMs(5000), constant.WithNotLoadCacheAtStart(true), constant.WithLogDir("/tmp/nacos/log"), constant.WithCacheDir("/tmp/nacos/cache"), constant.WithLogLevel("info"), ) sc := []constant.ServerConfig{ *constant.NewServerConfig("127.0.0.1", 8848, constant.WithContextPath("/nacos")), } client, err := clients.NewConfigClient(vo.NacosClientParam{ ClientConfig: &cc, ServerConfigs: sc, }) if err != nil { panic(err) } return client } ``` ``` -------------------------------- ### Enable Mutual TLS for gRPC Channel Source: https://context7.com/nacos-group/nacos-sdk-go/llms.txt Configures certificate-based authentication for secure server connections using NewTLSConfig. This example demonstrates creating a config client with TLS enabled. ```go package main import ( "github.com/nacos-group/nacos-sdk-go/v2/clients" "github.com/nacos-group/nacos-sdk-go/v2/common/constant" "github.com/nacos-group/nacos-sdk-go/v2/vo" ) func createTLSClient() { tlsCfg := constant.NewTLSConfig( constant.WithCA("/path/to/ca.crt", "nacos.example.com"), constant.WithCertificate("/path/to/client.crt", "/path/to/client.key"), ) cc := *constant.NewClientConfig( constant.WithNamespaceId(""), constant.WithTLS(*tlsCfg), ) sc := []constant.ServerConfig{ *constant.NewServerConfig("secure.nacos.io", 8848), } client, err := clients.NewConfigClient(vo.NacosClientParam{ ClientConfig: &cc, ServerConfigs: sc, }) if err != nil { panic(err) } _ = client } ``` -------------------------------- ### Get Configuration Info with Nacos Go SDK Source: https://github.com/nacos-group/nacos-sdk-go/blob/master/README.md Use GetConfig to retrieve the content of a configuration. Specify the DataId and Group to fetch the desired configuration. ```go content, err := configClient.GetConfig(vo.ConfigParam{ DataId: "dataId", Group: "group"}) ``` -------------------------------- ### Get All Service Names with Nacos Go SDK Source: https://github.com/nacos-group/nacos-sdk-go/blob/master/README.md Retrieve all service names using GetAllServicesInfo. Requires specifying the namespace, page number, and page size for pagination. ```go serviceInfos, err := namingClient.GetAllServicesInfo(vo.GetAllServiceInfoParam{ NameSpace: "0e83cc81-9d8c-4bb8-a28a-ff703187543f", PageNo: 1, PageSize: 10, }), ``` -------------------------------- ### Get Service Instances with Nacos Go SDK Source: https://github.com/nacos-group/nacos-sdk-go/blob/master/README.md Retrieve service instances using GetService. Specify the service name, group, and clusters to filter results. Supports retrieving all instances or only healthy ones. ```go services, err := namingClient.GetService(vo.GetServiceParam{ ServiceName: "demo.go", Clusters: []string{"cluster-a"}, // default value is DEFAULT GroupName: "group-a", // default value is DEFAULT_GROUP }) ``` ```go // SelectAllInstance return all instances,include healthy=false,enable=false,weight<=0 instances, err := namingClient.SelectAllInstances(vo.SelectAllInstancesParam{ ServiceName: "demo.go", GroupName: "group-a", // default value is DEFAULT_GROUP Clusters: []string{"cluster-a"}, // default value is DEFAULT }) ``` ```go // SelectInstances only return the instances of healthy=${HealthyOnly},enable=true and weight>0 instances, err := namingClient.SelectInstances(vo.SelectInstancesParam{ ServiceName: "demo.go", GroupName: "group-a", // default value is DEFAULT_GROUP Clusters: []string{"cluster-a"}, // default value is DEFAULT HealthyOnly: true, }) ``` -------------------------------- ### Get Service Details with Nacos Go SDK Source: https://context7.com/nacos-group/nacos-sdk-go/llms.txt Retrieves service metadata and all instances for a specified service, group, and cluster combination. Iterates through instances to display their details. ```go package main import ( "fmt" "github.com/nacos-group/nacos-sdk-go/v2/vo" ) func getService(client /* naming_client.INamingClient */) { svc, err := client.GetService(vo.GetServiceParam{ ServiceName: "demo.go", GroupName: "group-a", Clusters: []string{"cluster-a"}, }) if err != nil { fmt.Printf("GetService failed: %v\n", err) return } // svc.Name, svc.GroupName, svc.Hosts ([]model.Instance) fmt.Printf("Service: %s, instances: %d\n", svc.Name, len(svc.Hosts)) for _, inst := range svc.Hosts { fmt.Printf(" %s:%d weight=%.1f healthy=%v\n", inst.Ip, inst.Port, inst.Weight, inst.Healthy) } } ``` -------------------------------- ### GetConfig - Fetch Configuration Content Source: https://context7.com/nacos-group/nacos-sdk-go/llms.txt Retrieve the raw content of a configuration item using GetConfig. If KMS is enabled and the DataId starts with "cipher-", the decrypted value is returned. ```go package main import ( "fmt" "github.com/nacos-group/nacos-sdk-go/v2/vo" ) func getConfig(client /* config_client.IConfigClient */) { content, err := client.GetConfig(vo.ConfigParam{ DataId: "application.yaml", Group: "DEFAULT_GROUP", }) if err != nil { fmt.Printf("GetConfig failed: %v\n", err) return } fmt.Printf("Config content:\n%s\n", content) } ``` -------------------------------- ### Select One Healthy Instance with Nacos Go SDK Source: https://github.com/nacos-group/nacos-sdk-go/blob/master/README.md Use SelectOneHealthyInstance to get a single healthy instance using the WRR (Weighted Round Robin) strategy. The instance must be health=true, enable=true, and weight>0. ```go // SelectOneHealthyInstance return one instance by WRR strategy for load balance // And the instance should be health=true,enable=true and weight>0 instance, err := namingClient.SelectOneHealthyInstance(vo.SelectOneHealthInstanceParam{ ServiceName: "demo.go", GroupName: "group-a", // default value is DEFAULT_GROUP Clusters: []string{"cluster-a"}, // default value is DEFAULT }) ``` -------------------------------- ### Create Nacos Client Configuration Source: https://github.com/nacos-group/nacos-sdk-go/blob/master/README.md Demonstrates two ways to create client configurations for Nacos SDK. Use this for setting up connection details, logging, and caching. ```go //create clientConfig clientConfig := constant.ClientConfig{ NamespaceId: "e525eafa-f7d7-4029-83d9-008937f9d468", //we can create multiple clients with different namespaceId to support multiple namespace.When namespace is public, fill in the blank string here. TimeoutMs: 5000, NotLoadCacheAtStart: true, LogDir: "/tmp/nacos/log", CacheDir: "/tmp/nacos/cache", LogLevel: "debug", } //Another way of create clientConfig clientConfig := *constant.NewClientConfig( constant.WithNamespaceId("e525eafa-f7d7-4029-83d9-008937f9d468"), //When namespace is public, fill in the blank string here. constant.WithTimeoutMs(5000), constant.WithNotLoadCacheAtStart(true), constant.WithLogDir("/tmp/nacos/log"), constant.WithCacheDir("/tmp/nacos/cache"), constant.WithLogLevel("debug"), ) ``` -------------------------------- ### Build Client Configuration with Functional Options Source: https://context7.com/nacos-group/nacos-sdk-go/llms.txt Creates a ClientConfig struct to control timeouts, caching, logging, authentication, KMS, and TLS. Use With* option functions to override default fields. ```go package main import ( "time" "github.com/nacos-group/nacos-sdk-go/v2/common/constant" ) func buildClientConfig() constant.ClientConfig { return *constant.NewClientConfig( constant.WithNamespaceId("e525eafa-f7d7-4029-83d9-008937f9d468"), // public namespace = "" constant.WithTimeoutMs(5000), constant.WithBeatInterval(3000), constant.WithNotLoadCacheAtStart(true), constant.WithUpdateCacheWhenEmpty(true), constant.WithUsername("nacos"), constant.WithPassword("nacos"), constant.WithLogDir("/tmp/nacos/log"), constant.WithCacheDir("/tmp/nacos/cache"), constant.WithLogLevel("info"), // debug | info | warn | error constant.WithLogSampling(time.Second, 100, 100), // tick, initial, thereafter constant.WithLogRollingConfig(&constant.ClientLogRollingConfig{ MaxSize: 100, // MB MaxAge: 3, // days MaxBackups: 5, Compress: true, }), ) } ``` -------------------------------- ### Select One Healthy Instance with WRR Load Balancing Source: https://context7.com/nacos-group/nacos-sdk-go/llms.txt Use this to pick a single healthy instance for client-side load balancing before making an upstream call. It employs a weighted round-robin strategy. ```go package main import ( "fmt" "net/http" "github.com/nacos-group/nacos-sdk-go/v2/vo" ) func callUpstream(client /* naming_client.INamingClient */) { inst, err := client.SelectOneHealthyInstance(vo.SelectOneHealthInstanceParam{ ServiceName: "demo.go", GroupName: "group-a", Clusters: []string{"cluster-a"}, }) if err != nil { fmt.Printf("SelectOneHealthyInstance failed: %v\n", err) return } // inst.Ip, inst.Port, inst.Metadata url := fmt.Sprintf("http://%s:%d/api/hello", inst.Ip, inst.Port) resp, err := http.Get(url) if err != nil { fmt.Printf("HTTP call failed: %v\n", err) return } defer resp.Body.Close() fmt.Printf("Response status: %s\n", resp.Status) } ``` -------------------------------- ### constant.NewClientConfig Source: https://context7.com/nacos-group/nacos-sdk-go/llms.txt Build a client configuration with functional options to control timeouts, caching, logging, authentication, KMS, and TLS. All fields have sensible defaults; use `With*` option functions to override them. ```APIDOC ## constant.NewClientConfig ### Description Creates a `ClientConfig` struct controlling timeouts, caching, logging, authentication, KMS, and TLS. All fields have sensible defaults; use `With*` option functions to override them. ### Usage ```go package main import ( "time" "github.com/nacos-group/nacos-sdk-go/v2/common/constant" ) func buildClientConfig() constant.ClientConfig { return *constant.NewClientConfig( constant.WithNamespaceId("e525eafa-f7d7-4029-83d9-008937f9d468"), // public namespace = "" constant.WithTimeoutMs(5000), constant.WithBeatInterval(3000), constant.WithNotLoadCacheAtStart(true), constant.WithUpdateCacheWhenEmpty(true), constant.WithUsername("nacos"), constant.WithPassword("nacos"), constant.WithLogDir("/tmp/nacos/log"), constant.WithCacheDir("/tmp/nacos/cache"), constant.WithLogLevel("info"), // debug | info | warn | error constant.WithLogSampling(time.Second, 100, 100), // tick, initial, thereafter constant.WithLogRollingConfig(&constant.ClientLogRollingConfig{ MaxSize: 100, // MB MaxAge: 3, // days MaxBackups: 5, Compress: true, }), ) } ``` ``` -------------------------------- ### Create Nacos Naming and Config Clients Source: https://github.com/nacos-group/nacos-sdk-go/blob/master/README.md Instantiates Nacos clients for service discovery and configuration management using both direct and recommended `NewClient` methods. Ensure server and client configurations are correctly set. ```go // Create naming client for service discovery _, _ := clients.CreateNamingClient(map[string]interface{}{ "serverConfigs": serverConfigs, "clientConfig": clientConfig, }) // Create config client for dynamic configuration _, _ := clients.CreateConfigClient(map[string]interface{}{ "serverConfigs": serverConfigs, "clientConfig": clientConfig, }) // Another way of create naming client for service discovery (recommend) namingClient, err := clients.NewNamingClient( vo.NacosClientParam{ ClientConfig: &clientConfig, ServerConfigs: serverConfigs, }, ) // Another way of create config client for dynamic configuration (recommend) configClient, err := clients.NewConfigClient( vo.NacosClientParam{ ClientConfig: &clientConfig, ServerConfigs: serverConfigs, }, ) ``` -------------------------------- ### ListenConfig - Subscribe to Configuration Changes Source: https://context7.com/nacos-group/nacos-sdk-go/llms.txt Subscribe to real-time configuration changes using ListenConfig. An OnChange callback function is executed when the specified configuration is updated. Multiple configurations can be monitored simultaneously. ```go package main import ( "fmt" "sync" "time" "github.com/nacos-group/nacos-sdk-go/v2/vo" ) func listenConfig(client /* config_client.IConfigClient */) { var mu sync.Mutex currentConfig := "" err := client.ListenConfig(vo.ConfigParam{ DataId: "application.yaml", Group: "DEFAULT_GROUP", OnChange: func(namespace, group, dataId, data string) { mu.Lock() defer mu.Unlock() currentConfig = data fmt.Printf("[%s] Config changed — namespace=%s group=%s dataId=%s\n%s\n", time.Now().Format(time.RFC3339), namespace, group, dataId, data) }, }) if err != nil { fmt.Printf("ListenConfig failed: %v\n", err) return } fmt.Println("Listening for config changes...") // Access the latest value at any time mu.Lock() fmt.Printf("Current config: %s\n", currentConfig) mu.Unlock() } ``` -------------------------------- ### Create Nacos Naming Client Source: https://context7.com/nacos-group/nacos-sdk-go/llms.txt Initializes an INamingClient for service registration, discovery, and subscription. Ensure Nacos server is running and accessible. ```go package main import ( "github.com/nacos-group/nacos-sdk-go/v2/clients" "github.com/nacos-group/nacos-sdk-go/v2/clients/naming_client" "github.com/nacos-group/nacos-sdk-go/v2/common/constant" "github.com/nacos-group/nacos-sdk-go/v2/vo" ) func newNamingClient() naming_client.INamingClient { cc := *constant.NewClientConfig( constant.WithNamespaceId(""), constant.WithTimeoutMs(5000), constant.WithNotLoadCacheAtStart(true), constant.WithLogDir("/tmp/nacos/log"), constant.WithCacheDir("/tmp/nacos/cache"), constant.WithLogLevel("info"), ) sc := []constant.ServerConfig{ *constant.NewServerConfig("127.0.0.1", 8848, constant.WithContextPath("/nacos")), } client, err := clients.NewNamingClient(vo.NacosClientParam{ ClientConfig: &cc, ServerConfigs: sc, }) if err != nil { panic(err) } return client } ``` -------------------------------- ### Register Instance with Nacos Go SDK Source: https://github.com/nacos-group/nacos-sdk-go/blob/master/README.md Use RegisterInstance to register a service instance. Specify details like IP, port, service name, weight, and metadata. Ephemeral instances are supported. ```go success, err := namingClient.RegisterInstance(vo.RegisterInstanceParam{ Ip: "10.0.0.11", Port: 8848, ServiceName: "demo.go", Weight: 10, Enable: true, Healthy: true, Ephemeral: true, Metadata: map[string]string{"idc":"shanghai"}, ClusterName: "cluster-a", // default value is DEFAULT GroupName: "group-a", // default value is DEFAULT_GROUP }) ``` -------------------------------- ### SelectInstances Source: https://github.com/nacos-group/nacos-sdk-go/blob/master/README.md Retrieves instances for a given service that are healthy and enabled, with positive weight. ```APIDOC ## SelectInstances ### Description Retrieves instances for a given service that are healthy and enabled, with positive weight. ### Method ```go namingClient.SelectInstances ``` ### Parameters #### Request Body - **vo.SelectInstancesParam** (object) - Required - Parameters for selecting instances. - **ServiceName** (string) - Required - The name of the service. - **GroupName** (string) - Optional - The group name (default: DEFAULT_GROUP). - **Clusters** ([]string) - Optional - The list of clusters (default: DEFAULT). - **HealthyOnly** (bool) - Optional - Whether to return only healthy instances (default: false). ### Request Example ```go // SelectInstances only return the instances of healthy=${HealthyOnly},enable=true and weight>0 instances, err := namingClient.SelectInstances(vo.SelectInstancesParam{ ServiceName: "demo.go", GroupName: "group-a", // default value is DEFAULT_GROUP Clusters: []string{"cluster-a"}, // default value is DEFAULT HealthyOnly: true, }) ``` ``` -------------------------------- ### SelectAllInstances Source: https://github.com/nacos-group/nacos-sdk-go/blob/master/README.md Retrieves all instances for a given service, including unhealthy and disabled ones. ```APIDOC ## SelectAllInstances ### Description Retrieves all instances for a given service, including unhealthy and disabled ones. ### Method ```go namingClient.SelectAllInstances ``` ### Parameters #### Request Body - **vo.SelectAllInstancesParam** (object) - Required - Parameters for selecting all instances. - **ServiceName** (string) - Required - The name of the service. - **GroupName** (string) - Optional - The group name (default: DEFAULT_GROUP). - **Clusters** ([]string) - Optional - The list of clusters (default: DEFAULT). ### Request Example ```go // SelectAllInstance return all instances,include healthy=false,enable=false,weight<=0 instances, err := namingClient.SelectAllInstances(vo.SelectAllInstancesParam{ ServiceName: "demo.go", GroupName: "group-a", // default value is DEFAULT_GROUP Clusters: []string{"cluster-a"}, // default value is DEFAULT }) ``` ``` -------------------------------- ### Select All Instances with Nacos Go SDK Source: https://context7.com/nacos-group/nacos-sdk-go/llms.txt Returns all instances for a service, including unhealthy, disabled, and zero-weight ones. This is useful for debugging or administrative tasks. ```go package main import ( "fmt" "github.com/nacos-group/nacos-sdk-go/v2/vo" ) func selectAllInstances(client /* naming_client.INamingClient */) { instances, err := client.SelectAllInstances(vo.SelectAllInstancesParam{ ServiceName: "demo.go", GroupName: "group-a", Clusters: []string{"cluster-a"}, }) if err != nil { fmt.Printf("SelectAllInstances failed: %v\n", err) return } fmt.Printf("Total instances (all states): %d\n", len(instances)) } ``` -------------------------------- ### Create Nacos Server Configuration Source: https://github.com/nacos-group/nacos-sdk-go/blob/master/README.md Shows two methods for defining Nacos server configurations, including IP address, port, context path, and scheme. Essential for connecting to Nacos clusters. ```go // At least one ServerConfig serverConfigs := []constant.ServerConfig{ { IpAddr: "console1.nacos.io", ContextPath: "/nacos", Port: 80, Scheme: "http", }, { IpAddr: "console2.nacos.io", ContextPath: "/nacos", Port: 80, Scheme: "http", }, } //Another way of create serverConfigs serverConfigs := []constant.ServerConfig{ *constant.NewServerConfig( "console1.nacos.io", 80, constant.WithScheme("http"), constant.WithContextPath("/nacos") ), *constant.NewServerConfig( "console2.nacos.io", 80, constant.WithScheme("http"), constant.WithContextPath("/nacos") ), } ``` -------------------------------- ### Subscribe to Real-time Service Change Events Source: https://context7.com/nacos-group/nacos-sdk-go/llms.txt Register a callback to be invoked when service instances change. Multiple callbacks can be registered for the same service key (serviceName+groupName+clusters). ```go package main import ( "fmt" "github.com/nacos-group/nacos-sdk-go/v2/model" "github.com/nacos-group/nacos-sdk-go/v2/util" "github.com/nacos-group/nacos-sdk-go/v2/vo" ) func subscribeService(client /* naming_client.INamingClient */) { param := &vo.SubscribeParam{ ServiceName: "demo.go", GroupName: "group-a", Clusters: []string{"cluster-a"}, SubscribeCallback: func(services []model.Instance, err error) { if err != nil { fmt.Printf("Subscribe callback error: %v\n", err) return } fmt.Printf("Service instances updated: %s\n", util.ToJsonString(services)) }, } if err := client.Subscribe(param); err != nil { fmt.Printf("Subscribe failed: %v\n", err) } } ``` -------------------------------- ### Listen for Configuration Changes with Nacos Go SDK Source: https://github.com/nacos-group/nacos-sdk-go/blob/master/README.md Use ListenConfig to set up a listener for configuration changes. Provide a callback function that will be executed when the configuration is updated. Specify DataId and Group. ```go err := configClient.ListenConfig(vo.ConfigParam{ DataId: "dataId", Group: "group", OnChange: func (namespace, group, dataId, data string) { fmt.Println("group:" + group + ", dataId:" + dataId + ", data:" + data) }, }) ``` -------------------------------- ### PublishConfig - Create or Update Configuration Source: https://context7.com/nacos-group/nacos-sdk-go/llms.txt Use PublishConfig to create a new configuration item or update an existing one. To enable KMS encryption, prefix the DataId with "cipher-". ```go package main import ( "fmt" "github.com/nacos-group/nacos-sdk-go/v2/vo" ) func publishConfig(client /* config_client.IConfigClient */) { success, err := client.PublishConfig(vo.ConfigParam{ DataId: "application.yaml", Group: "DEFAULT_GROUP", Content: "server:\n port: 8080\nspring:\n datasource:\n url: jdbc:mysql://localhost/mydb", }) if err != nil || !success { fmt.Printf("PublishConfig failed: %v\n", err) return } fmt.Println("Config published successfully") // Publish an encrypted config (KMS required, DataId must start with "cipher-") _, err = client.PublishConfig(vo.ConfigParam{ DataId: "cipher-db-password", Group: "DEFAULT_GROUP", Content: "my-secret-password", }) if err != nil { fmt.Printf("PublishConfig (encrypted) failed: %v\n", err) } } ``` -------------------------------- ### Paginate Through All Registered Services Source: https://context7.com/nacos-group/nacos-sdk-go/llms.txt Retrieve a paginated list of service names within a specified namespace and group. The loop continues until fewer than the page size number of services are returned. ```go package main import ( "fmt" "github.com/nacos-group/nacos-sdk-go/v2/vo" ) func listAllServices(client /* naming_client.INamingClient */) { page := 1 for { result, err := client.GetAllServicesInfo(vo.GetAllServiceInfoParam{ NameSpace: "0e83cc81-9d8c-4bb8-a28a-ff703187543f", // omit for default (public) GroupName: "group-a", PageNo: uint32(page), PageSize: 20, }) if err != nil { fmt.Printf("GetAllServicesInfo failed: %v\n", err) return } fmt.Printf("Page %d: %v\n", page, result.Doms) if int64(len(result.Doms)) < 20 { break } page++ } } ``` -------------------------------- ### GetAllServicesInfo Source: https://github.com/nacos-group/nacos-sdk-go/blob/master/README.md Retrieves a list of all service names within a specified namespace, with pagination. ```APIDOC ## GetAllServicesInfo ### Description Retrieves a list of all service names within a specified namespace, with pagination. ### Method ```go namingClient.GetAllServicesInfo ``` ### Parameters #### Request Body - **vo.GetAllServiceInfoParam** (object) - Required - Parameters for getting all service information. - **NameSpace** (string) - Required - The namespace ID. - **PageNo** (int) - Optional - The page number (default: 1). - **PageSize** (int) - Optional - The number of items per page (default: 10). ### Request Example ```go serviceInfos, err := namingClient.GetAllServicesInfo(vo.GetAllServiceInfoParam{ NameSpace: "0e83cc81-9d8c-4bb8-a28a-ff703187543f", PageNo: 1, PageSize: 10, }), ``` ``` -------------------------------- ### ListenConfig Source: https://github.com/nacos-group/nacos-sdk-go/blob/master/README.md Listens for changes to a specific configuration item. A callback function is invoked when the configuration is updated. ```APIDOC ## ListenConfig ### Description Listens for changes to a specific configuration item. A callback function is invoked when the configuration is updated. ### Method ```go configClient.ListenConfig ``` ### Parameters #### Request Body - **vo.ConfigParam** (object) - Required - Parameters for listening to configuration changes. - **DataId** (string) - Required - The Data ID of the configuration. - **Group** (string) - Required - The group of the configuration. - **OnChange** (func(string, string, string, string)) - Required - The callback function to execute on configuration change. ### Request Example ```go err := configClient.ListenConfig(vo.ConfigParam{ DataId: "dataId", Group: "group", OnChange: func (namespace, group, dataId, data string) { fmt.Println("group:" + group + ", dataId:" + dataId + ", data:" + data) }, }) ``` ``` -------------------------------- ### GetService Source: https://github.com/nacos-group/nacos-sdk-go/blob/master/README.md Retrieves service information, including instances, based on service name, group, and clusters. ```APIDOC ## GetService ### Description Retrieves service information, including instances, based on service name, group, and clusters. ### Method ```go namingClient.GetService ``` ### Parameters #### Request Body - **vo.GetServiceParam** (object) - Required - Parameters for getting service information. - **ServiceName** (string) - Required - The name of the service. - **Clusters** ([]string) - Optional - The list of clusters (default: DEFAULT). - **GroupName** (string) - Optional - The group name (default: DEFAULT_GROUP). ### Request Example ```go services, err := namingClient.GetService(vo.GetServiceParam{ ServiceName: "demo.go", Clusters: []string{"cluster-a"}, // default value is DEFAULT GroupName: "group-a", // default value is DEFAULT_GROUP }) ``` ``` -------------------------------- ### Search Configurations with Nacos Go SDK Source: https://github.com/nacos-group/nacos-sdk-go/blob/master/README.md Use SearchConfig to search for configurations. You can specify search keywords, DataId, Group, and pagination parameters. ```go configPage, err := configClient.SearchConfig(vo.SearchConfigParam{ Search: "blur", DataId: "", Group: "", PageNo: 1, PageSize: 10, }) ``` -------------------------------- ### Batch Register Service Instances Source: https://context7.com/nacos-group/nacos-sdk-go/llms.txt Registers multiple service instances atomically in a single RPC call. Instance-level ServiceName and GroupName are inherited from the outer parameter. ```go package main import ( "fmt" "github.com/nacos-group/nacos-sdk-go/v2/vo" ) func batchRegister(client /* naming_client.INamingClient */) { success, err := client.BatchRegisterInstance(vo.BatchRegisterInstanceParam{ ServiceName: "demo.go", GroupName: "group-a", Instances: []vo.RegisterInstanceParam{ {Ip: "10.0.0.10", Port: 8848, Weight: 10, Enable: true, Healthy: true, Ephemeral: true, ClusterName: "cluster-a", Metadata: map[string]string{"idc": "shanghai"}}, {Ip: "10.0.0.12", Port: 8848, Weight: 7, Enable: true, Healthy: true, Ephemeral: true, ClusterName: "cluster-a", Metadata: map[string]string{"idc": "beijing"}}, }, }) if err != nil || !success { fmt.Printf("BatchRegisterInstance failed: %v\n", err) return } fmt.Println("BatchRegisterInstance succeeded") } ``` -------------------------------- ### NewConfigClient with ACM endpoint Source: https://context7.com/nacos-group/nacos-sdk-go/llms.txt Connects to Alibaba Cloud ACM using a specified endpoint, optionally combining KMS encryption for secure config storage. ```APIDOC ## clients.NewConfigClient with ACM endpoint — Connect to Alibaba Cloud ACM Uses an Alibaba Cloud ACM endpoint instead of a self-hosted Nacos server. Combines KMS encryption for secure config storage. ### Method ```go clients.NewConfigClient(param vo.NacosClientParam) ``` ### Parameters #### Request Body (vo.NacosClientParam) - **ClientConfig** (*constant.ClientConfig) - Required - Client configuration object. - **Endpoint** (string) - Required - The ACM endpoint address (e.g., `acm.aliyun.com:8080`). - **NamespaceId** (string) - Required - The namespace ID for ACM. - **RegionId** (string) - Required - The region ID for ACM. - **AccessKey** (string) - Required - The Access Key ID for authentication. - **SecretKey** (string) - Required - The Access Key Secret for authentication. - **OpenKMS** (bool) - Optional - Enables KMS encryption/decryption. Defaults to false. - **KMSVersion** (string) - Optional - Specifies the KMS version (e.g., `constant.KMSv1`, `constant.KMSv3`). Required if `OpenKMS` is true. - **TimeoutMs** (int64) - Optional - The timeout in milliseconds for client operations. Defaults to 5000. - **LogLevel** (string) - Optional - The logging level (e.g., `info`, `error`). Defaults to `error`. - **ServerConfigs** ([]constant.ServerConfig) - Not used when an endpoint is provided for ACM. ### Request Example ```go cc := *constant.NewClientConfig( constant.WithEndpoint("acm.aliyun.com:8080"), constant.WithNamespaceId("e525eafa-f7d7-4029-83d9-008937f9d468"), constant.WithRegionId("cn-shanghai"), constant.WithAccessKey("LTAI4G8KxxxxxxxxxxxxxbwZLBr"), constant.WithSecretKey("n5jTL9YxxxxxxxxxxxxaxmPLZV9"), constant.WithOpenKMS(true), constant.WithKMSVersion(constant.KMSv1), constant.WithTimeoutMs(5000), constant.WithLogLevel("info"), ) client, err := clients.NewConfigClient(vo.NacosClientParam{ ClientConfig: &cc, }) ``` ### Usage Notes - DataIds starting with "cipher-" are automatically handled for encryption/decryption by KMS when `OpenKMS` is enabled. ### Response #### Success Response (clients.IConfigClient) - Returns an initialized `clients.IConfigClient` instance configured for ACM. #### Error Response - Returns an error if client creation fails. ``` -------------------------------- ### Publish Configuration with Nacos Go SDK Source: https://github.com/nacos-group/nacos-sdk-go/blob/master/README.md Use PublishConfig to publish configuration data. Specify the DataId, Group, and the content of the configuration. ```go success, err := configClient.PublishConfig(vo.ConfigParam{ DataId: "dataId", Group: "group", Content: "hello world!222222"}) ``` -------------------------------- ### RegisterInstance Source: https://github.com/nacos-group/nacos-sdk-go/blob/master/README.md Registers an instance with the Nacos service discovery. Allows specifying details like IP, port, service name, weight, health status, and metadata. ```APIDOC ## RegisterInstance ### Description Registers an instance with the Nacos service discovery. Allows specifying details like IP, port, service name, weight, health status, and metadata. ### Method ```go namingClient.RegisterInstance ``` ### Parameters #### Request Body - **vo.RegisterInstanceParam** (object) - Required - Parameters for registering an instance. - **Ip** (string) - Required - The IP address of the instance. - **Port** (int) - Required - The port of the instance. - **ServiceName** (string) - Required - The name of the service. - **Weight** (float64) - Optional - The weight of the instance (default: 1.0). - **Enable** (bool) - Optional - Whether the instance is enabled (default: true). - **Healthy** (bool) - Optional - Whether the instance is healthy (default: true). - **Ephemeral** (bool) - Optional - Whether the instance is ephemeral (default: true). - **Metadata** (map[string]string) - Optional - Metadata associated with the instance. - **ClusterName** (string) - Optional - The cluster name (default: DEFAULT). - **GroupName** (string) - Optional - The group name (default: DEFAULT_GROUP). ### Request Example ```go success, err := namingClient.RegisterInstance(vo.RegisterInstanceParam{ Ip: "10.0.0.11", Port: 8848, ServiceName: "demo.go", Weight: 10, Enable: true, Healthy: true, Ephemeral: true, Metadata: map[string]string{"idc":"shanghai"}, ClusterName: "cluster-a", // default value is DEFAULT GroupName: "group-a", // default value is DEFAULT_GROUP }) ``` ``` -------------------------------- ### BatchRegisterInstance Source: https://context7.com/nacos-group/nacos-sdk-go/llms.txt Registers a list of instances for the same service in a single RPC call. Instance-level `ServiceName` and `GroupName` are inherited from the outer param. ```APIDOC ## BatchRegisterInstance — Register multiple instances atomically Registers a list of instances for the same service in a single RPC call. Instance-level `ServiceName` and `GroupName` are inherited from the outer param. ```go package main import ( "fmt" "github.com/nacos-group/nacos-sdk-go/v2/vo" ) func batchRegister(client /* naming_client.INamingClient */) { success, err := client.BatchRegisterInstance(vo.BatchRegisterInstanceParam{ ServiceName: "demo.go", GroupName: "group-a", Instances: []vo.RegisterInstanceParam{ {Ip: "10.0.0.10", Port: 8848, Weight: 10, Enable: true, Healthy: true, Ephemeral: true, ClusterName: "cluster-a", Metadata: map[string]string{"idc": "shanghai"}}, {Ip: "10.0.0.12", Port: 8848, Weight: 7, Enable: true, Healthy: true, Ephemeral: true, ClusterName: "cluster-a", Metadata: map[string]string{"idc": "beijing"}}, }, }) if err != nil || !success { fmt.Printf("BatchRegisterInstance failed: %v\n", err) return } fmt.Println("BatchRegisterInstance succeeded") } ``` ``` -------------------------------- ### clients.NewNamingClient Source: https://context7.com/nacos-group/nacos-sdk-go/llms.txt Creates a new Nacos service discovery client (`INamingClient`) used for service registration, discovery, and subscription operations. ```APIDOC ## clients.NewNamingClient — Create a service-discovery client Returns an `INamingClient` used for all service registration, discovery, and subscription operations. ```go package main import ( "github.com/nacos-group/nacos-sdk-go/v2/clients" "github.com/nacos-group/nacos-sdk-go/v2/clients/naming_client" "github.com/nacos-group/nacos-sdk-go/v2/common/constant" "github.com/nacos-group/nacos-sdk-go/v2/vo" ) func newNamingClient() naming_client.INamingClient { cc := *constant.NewClientConfig( constant.WithNamespaceId(""), constant.WithTimeoutMs(5000), constant.WithNotLoadCacheAtStart(true), constant.WithLogDir("/tmp/nacos/log"), constant.WithCacheDir("/tmp/nacos/cache"), constant.WithLogLevel("info"), ) sc := []constant.ServerConfig{ *constant.NewServerConfig("127.0.0.1", 8848, constant.WithContextPath("/nacos")), } client, err := clients.NewNamingClient(vo.NacosClientParam{ ClientConfig: &cc, ServerConfigs: sc, }) if err != nil { panic(err) } return client } ``` ``` -------------------------------- ### SearchConfig Source: https://context7.com/nacos-group/nacos-sdk-go/llms.txt Searches across configuration items using either exact or fuzzy matching. Returns a paginated *model.ConfigPage. ```APIDOC ## SearchConfig — Query configuration items by DataId/Group Searches across configuration items using either exact (`search=accurate`) or fuzzy (`search=blur`) matching. Returns a paginated `*model.ConfigPage`. ### Method ```go client.SearchConfig(param vo.SearchConfigParam) ``` ### Parameters #### Request Body (vo.SearchConfigParam) - **Search** (string) - Required - Specifies the search mode: `accurate` or `blur`. - **DataId** (string) - Optional - The DataId to search for. Can be a partial match if `search` is `blur`. - **Group** (string) - Optional - The Group to search within. If empty, searches all groups. - **PageNo** (int) - Required - The page number for pagination. - **PageSize** (int) - Required - The number of items per page. ### Request Example (Fuzzy Search) ```go vo.SearchConfigParam{ Search: "blur", DataId: "application", // partial match Group: "", // all groups PageNo: 1, PageSize: 10, } ``` ### Request Example (Exact Search) ```go vo.SearchConfigParam{ Search: "accurate", DataId: "application.yaml", Group: "DEFAULT_GROUP", PageNo: 1, PageSize: 5, } ``` ### Response #### Success Response (*model.ConfigPage) - **TotalCount** (int) - The total number of configuration items found. - **PageNumber** (int) - The current page number. - **PagesAvailable** (int) - The total number of available pages. - **PageItems** ([]model.ConfigListItem) - A list of configuration items matching the search criteria. - **Group** (string) - The group of the configuration item. - **DataId** (string) - The DataId of the configuration item. - **Md5** (string) - The MD5 checksum of the configuration item content. ``` -------------------------------- ### Create Nacos Client for ACM Source: https://github.com/nacos-group/nacos-sdk-go/blob/master/README.md Configures and creates a Nacos client specifically for Aliyun ACM (Application Configuration Management). Requires ACM-specific endpoint, region, and credentials. ```go cc := constant.ClientConfig{ Endpoint: "acm.aliyun.com:8080", NamespaceId: "e525eafa-f7d7-4029-83d9-008937f9d468", RegionId: "cn-shanghai", AccessKey: "LTAI4G8KxxxxxxxxxxxxxbwZLBr", SecretKey: "n5jTL9YxxxxxxxxxxxxaxmPLZV9", OpenKMS: true, TimeoutMs: 5000, LogLevel: "debug", } // a more graceful way to create config client client, err := clients.NewConfigClient( vo.NacosClientParam{ ClientConfig: &cc, }, ) ``` -------------------------------- ### Connect to Alibaba Cloud ACM with KMS Encryption Source: https://context7.com/nacos-group/nacos-sdk-go/llms.txt Instantiate a ConfigClient using an ACM endpoint and KMS for secure configuration storage. DataIds prefixed with 'cipher-' are automatically handled by KMS. ```go package main import ( "fmt" "github.com/nacos-group/nacos-sdk-go/v2/clients" "github.com/nacos-group/nacos-sdk-go/v2/common/constant" "github.com/nacos-group/nacos-sdk-go/v2/vo" ) func createACMClient() { cc := *constant.NewClientConfig( constant.WithEndpoint("acm.aliyun.com:8080"), constant.WithNamespaceId("e525eafa-f7d7-4029-83d9-008937f9d468"), constant.WithRegionId("cn-shanghai"), constant.WithAccessKey("LTAI4G8KxxxxxxxxxxxxxbwZLBr"), constant.WithSecretKey("n5jTL9YxxxxxxxxxxxxaxmPLZV9"), constant.WithOpenKMS(true), constant.WithKMSVersion(constant.KMSv1), constant.WithTimeoutMs(5000), constant.WithLogLevel("info"), ) client, err := clients.NewConfigClient(vo.NacosClientParam{ ClientConfig: &cc, // No ServerConfigs needed — endpoint is used instead }) if err != nil { panic(err) } // DataIds starting with "cipher-" are auto-encrypted/decrypted by KMS _, err = client.PublishConfig(vo.ConfigParam{ DataId: "cipher-db-password", Group: "DEFAULT_GROUP", Content: "my-plaintext-secret", }) if err != nil { fmt.Printf("Publish encrypted config failed: %v\n", err) return } plaintext, err := client.GetConfig(vo.ConfigParam{ DataId: "cipher-db-password", Group: "DEFAULT_GROUP", }) if err != nil { fmt.Printf("Get encrypted config failed: %v\n", err) return } fmt.Printf("Decrypted value: %s\n", plaintext) // Output: my-plaintext-secret } ```