Configuration

go-doudou provides out-of-the-box support for local configuration files in dotenv and yaml formats, as well as Alibaba's Nacos and Ctrip's Apollo configuration centers. It can load configurations from local files or remote configuration centers into environment variables.

The priority between local configuration files and remote configuration centers is that local configuration files take precedence, meaning configurations already loaded from local files will not be overridden by those loaded from remote configuration centers.

Local Configuration Files

The usage of dotenv format and yaml format local configuration files is exactly the same, with only slight differences in file naming rules. These are explained separately below.

Tip

The two configuration file formats can be used simultaneously or you can use just one. When used simultaneously, yaml format configuration files are loaded first, and after all yaml files are loaded, dotenv format configuration files are loaded.

dotenv Files

If you have multiple .env files, such as .env.test, .env.prod, etc., to configure different environments, you can set the GDD_ENV environment variable to test or prod through the command line terminal, Dockerfile, or k8s configuration files to load the corresponding configuration file.

The configuration loading rules are as follows:

  1. For the same environment variable, whether configured in the command line terminal or through configuration files, the value loaded first has the highest priority and will not be modified by subsequently loaded values.
  2. The loading order of configuration files (taking the prod environment as an example) is: 1. Load .env.prod.local file 2. When the value of the environment variable GDD_ENV is not equal to test, load .env.local file 3. Load .env.prod file 4. Load .env file

Note: The prefix must be .env

yaml Files

Supports both .yml and .yaml suffix configuration files. If you have multiple yaml files, such as app-test.yml, app-prod.yml, etc., to configure different environments, you can set the GDD_ENV environment variable to test or prod through the command line terminal, Dockerfile, or k8s configuration files to load the corresponding configuration file.

The configuration loading rules are as follows:

  1. For the same environment variable, whether configured in the command line terminal or through configuration files, the value loaded first has the highest priority and will not be modified by subsequently loaded values.
  2. The loading order of configuration files (taking the prod environment as an example) is: 1. Load app-prod-local.yml file 2. When the value of the environment variable GDD_ENV is not equal to test, load app-local.yml file 3. Load app-prod.yml file 4. Load app.yml file

Note: The prefix must be app

Tip

When converting environment variables to yaml configuration, the rule is to use underscores as property separators. For very long property names, hyphens can be used to split them into multiple words for better readability. For example, the environment variable GDD_DB_MYSQL_DISABLEDATETIMEPRECISION converted to yaml configuration:

gdd:
	db:
		mysql:
			disable-datetime-precision:
1
2
3
4

Remote Configuration Solutions

go-doudou has built-in support for two remote configuration center solutions: Alibaba's Nacos and Ctrip's Apollo. It supports loading at service startup and also supports custom listener functions to monitor configuration changes.

To enable a remote configuration center, you need to configure the following environment variables in the local configuration file:

  • GDD_CONFIG_REMOTE_TYPE: Remote configuration center name, options: nacos, apollo

Tip

Some of the service configurations in the go-doudou framework layer (i.e., configurations with the GDD_ prefix) support runtime dynamic modification through remote configuration centers. The priority of runtime dynamic modifications is the highest and will override all configurations loaded from the command line terminal, Dockerfile, k8s configuration files, local configuration files, and remote configuration centers at service startup.

Nacos Configuration Center

go-doudou service will automatically load configurations from Nacos at startup. You only need to configure some parameters in the local configuration file, making it ready to use out of the box.

  • GDD_NACOS_NAMESPACE_ID: Nacos namespaceId, optional
  • GDD_NACOS_SERVER_ADDR: Nacos server connection address, required
  • GDD_NACOS_CONFIG_FORMAT: Configuration format, options: dotenv, yaml, default is dotenv
  • GDD_NACOS_CONFIG_GROUP: Nacos group, default is DEFAULT_GROUP
  • GDD_NACOS_CONFIG_DATAID: Nacos dataId, required, multiple dataIds separated by commas, the order in the configuration is the actual loading order, following the rule that configurations loaded first have the highest priority

The configmgr package provides an exported singleton NacosClient for interacting with the Nacos configuration center. You can call the AddChangeListener method to add custom listener functions. Example usage:

func main() {

	...

	if configmgr.NacosClient != nil {
		configmgr.NacosClient.AddChangeListener(configmgr.NacosConfigListenerParam{
			DataId: "statsvc-dev",
			OnChange: func(event *configmgr.NacosChangeEvent) {
				fmt.Println("group:" + event.Group + ", dataId:" + event.DataId + fmt.Sprintf(", changes: %+v\n", event.Changes))
			},
		})
	}

	...

	srv.Run()
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

Apollo Configuration Center

go-doudou service will automatically load configurations from Apollo at startup. You only need to configure some parameters in the local configuration file, making it ready to use out of the box.

  • GDD_SERVICE_NAME: Service name is the Apollo AppId
  • GDD_APOLLO_CLUSTER: Apollo cluster, default is default
  • GDD_APOLLO_ADDR: Apollo server connection address, required
  • GDD_APOLLO_NAMESPACE: Apollo namespace, equivalent to Nacos's dataId, default is application.properties, multiple namespaces separated by commas, the order in the configuration is the actual loading order, following the rule that configurations loaded first have the highest priority
  • GDD_APOLLO_SECRET: Apollo configuration secret, optional

The configmgr package provides an exported singleton ApolloClient for interacting with the Apollo configuration center. You can call the AddChangeListener method to add custom listener functions. Example usage:

type ConfigChangeListener struct {
	configmgr.BaseApolloListener
}

func (c *ConfigChangeListener) OnChange(event *storage.ChangeEvent) {
	c.Lock.Lock()
	defer c.Lock.Unlock()
	if !c.SkippedFirstEvent {
		c.SkippedFirstEvent = true
		return
	}
	logger.Info("from OnChange")
	fmt.Println(event.Changes)
	for key, value := range event.Changes {
		fmt.Println("change key : ", key, ", value :", value)
	}
	fmt.Println(event.Namespace)
	logger.Info("from OnChange end")
}

func main() {

    ...

	var listener ConfigChangeListener

	configmgr.ApolloClient.AddChangeListener(&listener)

    ...

	srv.Run()
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

It's worth noting that the first configuration loading event will also be detected by custom listener functions. If you need to skip the first time, you need to "inherit" the BaseApolloListener struct provided by the configmgr package, and then add the following code at the beginning of the OnChange function:

c.Lock.Lock()
defer c.Lock.Unlock()
if !c.SkippedFirstEvent {
  c.SkippedFirstEvent = true
  return
}
1
2
3
4
5
6

Service Configuration

Configurations marked with a red asterisk in the table are dynamically modified by go-doudou at runtime by monitoring configuration changes in the remote configuration center.

Environment VariableDescriptionDefault ValueRequired
GDD_BANNEREnable bannertrue
GDD_BANNER_TEXTBanner textgo-doudou
GDD_LOG_LEVELLog level, options: panic, fatal, error, warn, warning, info, debug, traceinfo
GDD_LOG_FORMATLog format, options: text, jsontext
GDD_LOG_REQ_ENABLEEnable HTTP request and response body loggingfalse
GDD_LOG_CALLERPrint "filename:line"true
GDD_LOG_DISCARDDisable loggingfalse
GDD_LOG_PATHLog file path, if set, logs will be written to the file
GDD_LOG_STYLELog format style, only valid when GDD_LOG_PATH is set, options: json or consolejson
GDD_GRACE_TIMEOUTGraceful shutdown timeout15s
GDD_WRITE_TIMEOUTHTTP connection write timeout15s
GDD_READ_TIMEOUTHTTP connection read timeout15s
GDD_IDLE_TIMEOUTHTTP connection idle timeout60s
GDD_ROUTE_ROOT_PATHHTTP request path prefix
GDD_SERVICE_NAMEService nameRequired
GDD_SERVICE_GROUPService group name, valid when using zookeeper for service registration and discovery
GDD_SERVICE_VERSIONService version name, valid when using zookeeper for service registration and discovery
GDD_HOSTHTTP server listening address
GDD_PORTHTTP server listening port6060
GDD_GRPC_PORTgRPC server listening port50051
GDD_RETRY_COUNTClient request retry count0
GDD_MANAGE_ENABLEEnable built-in HTTP interfaces: /go-doudou/doc, /go-doudou/openapi.json, /go-doudou/prometheus, /go-doudou/registry, /go-doudou/configtrue
*GDD_MANAGE_USERHTTP basic authentication username for built-in HTTP interfacesadmin
*GDD_MANAGE_PASSHTTP basic authentication password for built-in HTTP interfacesadmin
GDD_TRACING_METRICS_ROOTmetrics root for jaeger call chain monitoringtracing
GDD_WEIGHTService instance weight1
GDD_SERVICE_DISCOVERY_MODEService discovery mode, options: etcd, nacos, zk
GDD_ENABLE_RESPONSE_GZIPEnable HTTP response body gzip compressiontrue
GDD_SQL_LOG_ENABLEEnable SQL log printingfalse
GDD_REGISTER_HOSTService instance registration address, default is the host's private IP
GDD_FALLBACK_CONTENTTYPEDefault Content-Type header for HTTP response bodyapplication/json; charset=UTF-8
GDD_CONFIG_REMOTE_TYPERemote configuration center, options: nacos, apollo
GDD_ROUTER_SAVEMATCHEDROUTEPATHSave matched route pathtrue
GDD_STATS_FREQService status statistics frequency1s

Nacos Configuration

Environment VariableDescriptionDefault ValueRequired
GDD_NACOS_NAMESPACE_IDNamespacepublic
GDD_NACOS_TIMEOUT_MSRequest timeout in milliseconds10000
GDD_NACOS_NOTLOADCACHEATSTARTWhether to load service list from disk cache at program startupfalse
GDD_NACOS_LOG_DIRLog directory path/tmp/nacos/log
GDD_NACOS_CACHE_DIRService list disk cache path/tmp/nacos/cache
GDD_NACOS_LOG_LEVELLog level, options: debug, info, warn, errorinfo
GDD_NACOS_LOG_DISCARDDisable Nacos loggingfalse
GDD_NACOS_SERVER_ADDRNacos server connection address, multiple addresses separated by commas
GDD_NACOS_REGISTER_HOSTIP address used for Nacos service registration
GDD_NACOS_CLUSTER_NAMENacos cluster nameDEFAULT
GDD_NACOS_GROUP_NAMENacos group nameDEFAULT_GROUP
GDD_NACOS_CONFIG_FORMATConfiguration data format, supports: dotenv, yamldotenv
GDD_NACOS_CONFIG_GROUPConfiguration groupDEFAULT_GROUP
GDD_NACOS_CONFIG_DATAIDConfiguration dataIdRequired

Apollo Configuration

Environment VariableDescriptionDefault ValueRequired
GDD_APOLLO_CLUSTERApollo clusterdefault
GDD_APOLLO_ADDRApollo configuration service connection addressRequired
GDD_APOLLO_NAMESPACEApollo namespaceapplication.properties
GDD_APOLLO_BACKUP_ENABLEEnable configuration caching on local disktrue
GDD_APOLLO_BACKUP_PATHConfiguration cache folder path
GDD_APOLLO_MUSTSTARTReturn error immediately if configuration service connection failsfalse
GDD_APOLLO_SECRETApollo configuration secret
GDD_APOLLO_LOG_ENABLEEnable Apollo log printingfalse

Etcd Configuration

Environment VariableDescriptionDefault ValueRequired
GDD_ETCD_ENDPOINTSEtcd cluster connection address
GDD_ETCD_LEASEEtcd service registration lease TTL time in seconds5

Zookeeper Configuration

Environment VariableDescriptionDefault ValueRequired
GDD_ZK_SERVERSZookeeper cluster connection address, multiple addresses separated by commas
GDD_ZK_SEQUENCEWhether to add a sequence number to Zookeeper nodesfalse
GDD_ZK_DIRECTORY_PATTERNString fmt pattern for service registration node path, %s represents service name/registry/%s/providers

Memberlist Configuration

Memberlist is a built-in service registration and discovery component in the go-doudou framework based on the gossip protocol.

Environment VariableDescriptionDefault ValueRequired
GDD_MEM_SEEDCluster seed nodes for joining
GDD_MEM_NAMEUnique name of the node in the cluster, hostname will be used if not set
GDD_MEM_HOSTAdvertise address of the node, if starting with a dot (like .seed-svc), will be prefixed with hostname, supports K8s stateful services
GDD_MEM_PORTNode communication port, randomly assigned if not set7946
GDD_MEM_DEAD_TIMEOUTNode death timeout in seconds, node will be removed if no refute messages are received within this time60s
GDD_MEM_SYNC_INTERVALNode state synchronization interval in seconds60s
GDD_MEM_RECLAIM_TIMEOUTDead node reclamation time in seconds, dead node will be replaced by a new node after this time3s
GDD_MEM_PROBE_INTERVALProbe interval in seconds5s
GDD_MEM_PROBE_TIMEOUTProbe timeout in seconds3s
GDD_MEM_SUSPICION_MULTSuspicion multiplier, determines the time a node is considered suspicious before being declared dead6
GDD_MEM_RETRANSMIT_MULTRetransmission multiplier4
GDD_MEM_GOSSIP_NODESNumber of remote nodes to gossip messages to4
GDD_MEM_GOSSIP_INTERVALGossip interval in seconds500ms
GDD_MEM_TCP_TIMEOUTTCP timeout in seconds30s
GDD_MEM_WEIGHTNode weight1
GDD_MEM_WEIGHT_INTERVALNode weight calculation interval0
GDD_MEM_INDIRECT_CHECKSNumber of indirect checks3
GDD_MEM_LOG_DISABLEDisable memberlist loggingfalse
GDD_MEM_CIDRS_ALLOWEDCIDRs allowed to connect, allows any connection if not set, must specify IPv6/IPv4 separately

Cache Configuration

Environment VariableDescriptionDefault ValueRequired
GDD_CACHE_TTLCache TTL time in seconds0
GDD_CACHE_STORESCache storage types, options: redis, ristretto, gocache
GDD_CACHE_REDIS_ADDRRedis server address
GDD_CACHE_REDIS_USERRedis username
GDD_CACHE_REDIS_PASSRedis password
GDD_CACHE_REDIS_ROUTEBYLATENCYRoute Redis requests by latencytrue
GDD_CACHE_REDIS_ROUTERANDOMLYRoute Redis requests randomlyfalse
GDD_CACHE_RISTRETTO_NUMCOUNTERSRistretto cache counter number1000
GDD_CACHE_RISTRETTO_MAXCOSTRistretto cache maximum cost100
GDD_CACHE_RISTRETTO_BUFFERITEMSRistretto cache buffer items64
GDD_CACHE_GOCACHE_EXPIRATIONGoCache default cache expiration time5m
GDD_CACHE_GOCACHE_CLEANUP_INTERVALGoCache cleanup interval10m

Gorm Configuration

Environment VariableDescriptionDefault ValueRequired
GDD_DB_DISABLEAUTOCONFIGUREDisable auto-configurationfalse
GDD_DB_DRIVERDatabase driver name, consistent with gorm: mysql, postgres, sqlite, sqlserver, tidb, clickhouse
GDD_DB_DSNDatabase connection address
GDD_DB_TABLE_PREFIXDatabase table prefix
GDD_DB_PREPARESTMTEnable prepared statementsfalse
GDD_DB_SKIPDEFAULTTRANSACTIONSkip default transactionfalse
GDD_DB_POOL_MAXIDLECONNSMaximum number of idle connections2
GDD_DB_POOL_MAXOPENCONNSMaximum number of connections, -1 means unlimited-1
GDD_DB_POOL_CONNMAXLIFETIMEMaximum time period a connection can be reused, -1 means unlimited-1
GDD_DB_POOL_CONNMAXIDLETIMEMaximum idle time for a connection, if it expires it will be closed before reuse, -1 means unlimited-1
GDD_DB_LOG_SLOWTHRESHOLDSlow query log threshold200ms
GDD_DB_LOG_IGNORERECORDNOTFOUNDERRORIgnore record not found errorfalse
GDD_DB_LOG_PARAMETERIZEDQUERIESHide SQL parametersfalse
GDD_DB_LOG_LEVELLog level, consistent with gorm: silent, error, warn, infowarn
GDD_DB_MYSQL_SKIPINITIALIZEWITHVERSIONGorm's SkipInitializeWithVersion parameterfalse
GDD_DB_MYSQL_DEFAULTSTRINGSIZEGorm's DefaultStringSize parameter0
GDD_DB_MYSQL_DISABLEWITHRETURNINGGorm's DisableWithReturning parameterfalse
GDD_DB_MYSQL_DISABLEDATETIMEPRECISIONGorm's DisableDatetimePrecision parameterfalse
GDD_DB_MYSQL_DONTSUPPORTRENAMEINDEXGorm's DontSupportRenameIndex parameterfalse
GDD_DB_MYSQL_DONTSUPPORTRENAMECOLUMNGorm's DontSupportRenameColumn parameterfalse
GDD_DB_MYSQL_DONTSUPPORTFORSHARECLAUSEGorm's DontSupportForShareClause parameterfalse
GDD_DB_MYSQL_DONTSUPPORTNULLASDEFAULTVALUEGorm's DontSupportNullAsDefaultValue parameterfalse
GDD_DB_MYSQL_DONTSUPPORTRENAMECOLUMNUNIQUEGorm's DontSupportRenameColumnUnique parameterfalse
GDD_DB_POSTGRES_PREFERSIMPLEPROTOCOLGorm's PreferSimpleProtocol parameterfalse
GDD_DB_POSTGRES_WITHOUTRETURNINGGorm's WithoutReturning parameterfalse
GDD_DB_PROMETHEUS_ENABLEEnable Prometheus monitoringfalse
GDD_DB_PROMETHEUS_REFRESHINTERVALPrometheus monitoring refresh interval in seconds15
GDD_DB_PROMETHEUS_DBNAMEDatabase name used for Prometheus monitoring
GDD_DB_CACHE_ENABLEEnable database query cachingfalse