From e8596c5c2a93ed725460ff9ecce08274a4f9083c Mon Sep 17 00:00:00 2001 From: Mostafa Moradian Date: Sun, 6 Oct 2024 22:36:47 +0200 Subject: [PATCH] Refactor `interface{}` to `any` (#614) --- act/registry.go | 2 +- act/registry_test.go | 10 ++-- api/api.go | 2 +- api/api_test.go | 6 +- api/http_server_test.go | 2 +- cmd/configs.go | 2 +- cmd/plugin_install.go | 6 +- cmd/plugin_scaffold_test.go | 4 +- cmd/run.go | 20 +++---- config/config.go | 18 +++--- config/config_test.go | 6 +- logging/hclog_adapter.go | 24 ++++---- metrics/merger.go | 8 +-- network/client.go | 4 +- network/proxy.go | 58 +++++++++---------- network/retry.go | 2 +- network/server.go | 30 +++++----- network/utils.go | 12 ++-- network/utils_test.go | 2 +- .../{{ plugin_name }}/plugin/module.go | 14 ++--- .../{{ plugin_name }}/plugin/plugin.go | 2 +- plugin/plugin_registry.go | 6 +- plugin/plugin_registry_test.go | 4 +- plugin/plugin_scaffold.go | 6 +- plugin/utils.go | 12 ++-- plugin/utils_test.go | 20 +++---- pool/pool.go | 24 ++++---- pool/pool_test.go | 6 +- 28 files changed, 156 insertions(+), 156 deletions(-) diff --git a/act/registry.go b/act/registry.go index 4e46f286..c4cab57a 100644 --- a/act/registry.go +++ b/act/registry.go @@ -376,7 +376,7 @@ func runActionWithTimeout( if !action.Sync { execMode = "async" } - logger.Debug().Fields(map[string]interface{}{ + logger.Debug().Fields(map[string]any{ "executionMode": execMode, "action": action.Name, }).Msgf("Running action") diff --git a/act/registry_test.go b/act/registry_test.go index b9d16ada..d2f54bdb 100644 --- a/act/registry_test.go +++ b/act/registry_test.go @@ -309,7 +309,7 @@ func Test_Apply_ContradictorySignals(t *testing.T) { t, buf.String(), "Terminal signal takes precedence, ignoring non-terminal signals") assert.Equal(t, "log", outputs[1].MatchedPolicy) assert.Equal(t, - map[string]interface{}{ + map[string]any{ "async": true, "level": "info", "log": true, @@ -646,7 +646,7 @@ func Test_Run_Terminate(t *testing.T) { }) assert.NotNil(t, outputs) assert.Equal(t, "terminate", outputs[0].MatchedPolicy) - assert.Equal(t, outputs[0].Metadata, map[string]interface{}{"terminate": true}) + assert.Equal(t, outputs[0].Metadata, map[string]any{"terminate": true}) assert.True(t, outputs[0].Sync) assert.True(t, cast.ToBool(outputs[0].Verdict)) assert.True(t, outputs[0].Terminal) @@ -685,7 +685,7 @@ func Test_Run_Async(t *testing.T) { assert.NotNil(t, outputs) assert.Equal(t, "log", outputs[0].MatchedPolicy) assert.Equal(t, - map[string]interface{}{ + map[string]any{ "async": true, "level": "info", "log": true, @@ -764,7 +764,7 @@ func Test_Run_Async_Redis(t *testing.T) { assert.NotNil(t, outputs) assert.Equal(t, "log", outputs[0].MatchedPolicy) assert.Equal(t, - map[string]interface{}{ + map[string]any{ "async": true, "level": "info", "log": true, @@ -900,7 +900,7 @@ func Test_Run_Timeout(t *testing.T) { assert.NotNil(t, outputs) assert.Equal(t, name, outputs[0].MatchedPolicy) assert.Equal(t, - map[string]interface{}{ + map[string]any{ "async": isAsync, "level": "info", "log": true, diff --git a/api/api.go b/api/api.go index b457f047..d394752a 100644 --- a/api/api.go +++ b/api/api.go @@ -64,7 +64,7 @@ func (a *API) GetGlobalConfig(_ context.Context, group *v1.Group) (*structpb.Str var ( jsonData []byte - global map[string]interface{} + global map[string]any err error ) diff --git a/api/api_test.go b/api/api_test.go index 2d24b9a9..a1f0287e 100644 --- a/api/api_test.go +++ b/api/api_test.go @@ -81,7 +81,7 @@ func TestGetGlobalConfigWithGroupName(t *testing.T) { assert.NotEmpty(t, globalconf["servers"]) assert.NotEmpty(t, globalconf["metrics"]) assert.NotEmpty(t, globalconf["api"]) - if _, ok := globalconf["loggers"].(map[string]interface{})[config.Default]; !ok { + if _, ok := globalconf["loggers"].(map[string]any)[config.Default]; !ok { t.Errorf("loggers.default is not found") } } @@ -374,7 +374,7 @@ func TestGetServers(t *testing.T) { assert.NotEmpty(t, servers) assert.NotEmpty(t, servers.AsMap()) - if defaultServer, ok := servers.AsMap()[config.Default].(map[string]interface{}); ok { + if defaultServer, ok := servers.AsMap()[config.Default].(map[string]any); ok { assert.Equal(t, config.DefaultNetwork, defaultServer["network"]) statusFloat, isStatusFloat := defaultServer["status"].(float64) assert.True(t, isStatusFloat, "status should be of type float64") @@ -383,7 +383,7 @@ func TestGetServers(t *testing.T) { tickIntervalFloat, isTickIntervalFloat := defaultServer["tickInterval"].(float64) assert.True(t, isTickIntervalFloat, "tickInterval should be of type float64") assert.Equal(t, config.DefaultTickInterval.Nanoseconds(), int64(tickIntervalFloat)) - loadBalancerMap, isLoadBalancerMap := defaultServer["loadBalancer"].(map[string]interface{}) + loadBalancerMap, isLoadBalancerMap := defaultServer["loadBalancer"].(map[string]any) assert.True(t, isLoadBalancerMap, "loadBalancer should be a map") assert.Equal(t, config.DefaultLoadBalancerStrategy, loadBalancerMap["strategy"]) } else { diff --git a/api/http_server_test.go b/api/http_server_test.go index a8aaf9dd..77a6e36c 100644 --- a/api/http_server_test.go +++ b/api/http_server_test.go @@ -46,7 +46,7 @@ func Test_HTTP_Server(t *testing.T) { defer resp.Body.Close() assert.Equal(t, http.StatusOK, resp.StatusCode) assert.Equal(t, "application/json", resp.Header.Get("Content-Type")) - var respBody map[string]interface{} + var respBody map[string]any err = json.NewDecoder(resp.Body).Decode(&respBody) require.NoError(t, err) assert.Equal(t, config.Version, respBody["version"]) diff --git a/cmd/configs.go b/cmd/configs.go index 99b56516..5baf9185 100644 --- a/cmd/configs.go +++ b/cmd/configs.go @@ -117,7 +117,7 @@ func lintConfig(fileType configFileType, configFile string) *gerr.GatewayDError } // Unmarshal the JSON data into a map. - var jsonBytes map[string]interface{} + var jsonBytes map[string]any err = json.Unmarshal(jsonData, &jsonBytes) if err != nil { return gerr.ErrLintingFailed.Wrap(err) diff --git a/cmd/plugin_install.go b/cmd/plugin_install.go index d43e613d..e7015558 100644 --- a/cmd/plugin_install.go +++ b/cmd/plugin_install.go @@ -109,7 +109,7 @@ var pluginInstallCmd = &cobra.Command{ } // Get the registered plugins from the plugins configuration file. - var localPluginsConfig map[string]interface{} + var localPluginsConfig map[string]any if err := yamlv3.Unmarshal(pluginsConfig, &localPluginsConfig); err != nil { cmd.Println("Failed to unmarshal the plugins configuration file: ", err) return @@ -756,7 +756,7 @@ func installPlugin(cmd *cobra.Command, pluginURL string) { } // Get the registered plugins from the plugins configuration file. - var localPluginsConfig map[string]interface{} + var localPluginsConfig map[string]any if err := yamlv3.Unmarshal(pluginsConfig, &localPluginsConfig); err != nil { cmd.Println("Failed to unmarshal the plugins configuration file: ", err) return @@ -881,7 +881,7 @@ func installPlugin(cmd *cobra.Command, pluginURL string) { } // Get the plugin configuration from the downloaded plugins configuration file. - var downloadedPluginConfig map[string]interface{} + var downloadedPluginConfig map[string]any if err := yamlv3.Unmarshal([]byte(contents), &downloadedPluginConfig); err != nil { cmd.Println("Failed to unmarshal the downloaded plugins configuration file: ", err) return diff --git a/cmd/plugin_scaffold_test.go b/cmd/plugin_scaffold_test.go index 3a3cc183..88c6d75a 100644 --- a/cmd/plugin_scaffold_test.go +++ b/cmd/plugin_scaffold_test.go @@ -49,7 +49,7 @@ func Test_pluginScaffoldCmd(t *testing.T) { pluginsConfig, err := os.ReadFile(filepath.Join(pluginDir, "gatewayd_plugin.yaml")) require.NoError(t, err, "reading plugins config file should not return an error") - var localPluginsConfig map[string]interface{} + var localPluginsConfig map[string]any err = yamlv3.Unmarshal(pluginsConfig, &localPluginsConfig) require.NoError(t, err, "unmarshalling yaml file should not return error") @@ -71,7 +71,7 @@ func Test_pluginScaffoldCmd(t *testing.T) { plugin["checksum"] = sum pluginsList[0] = plugin - plugins := make(map[string]interface{}) + plugins := make(map[string]any) plugins["plugins"] = pluginsList updatedPluginConfig, err := yamlv3.Marshal(plugins) diff --git a/cmd/run.go b/cmd/run.go index d18d4d23..98a96061 100644 --- a/cmd/run.go +++ b/cmd/run.go @@ -111,7 +111,7 @@ func StopGracefully( //nolint:contextcheck _, err := pluginRegistry.Run( pluginTimeoutCtx, - map[string]interface{}{"signal": currentSignal}, + map[string]any{"signal": currentSignal}, v1.HookName_HOOK_NAME_ON_SIGNAL, ) if err != nil { @@ -332,7 +332,7 @@ var runCmd = &cobra.Command{ } } - logger.Info().Fields(map[string]interface{}{ + logger.Info().Fields(map[string]any{ "policies": maps.Keys(actRegistry.Policies), }).Msg("Policies are loaded") @@ -561,7 +561,7 @@ var runCmd = &cobra.Command{ IdleTimeout: timeout, } - logger.Info().Fields(map[string]interface{}{ + logger.Info().Fields(map[string]any{ "address": address, "timeout": timeout.String(), "readHeaderTimeout": readHeaderTimeout.String(), @@ -605,7 +605,7 @@ var runCmd = &cobra.Command{ pluginTimeoutCtx, cancel = context.WithTimeout(context.Background(), conf.Plugin.Timeout) defer cancel() - if data, ok := conf.GlobalKoanf.Get("loggers").(map[string]interface{}); ok { + if data, ok := conf.GlobalKoanf.Get("loggers").(map[string]any); ok { _, err = pluginRegistry.Run( pluginTimeoutCtx, data, v1.HookName_HOOK_NAME_ON_NEW_LOGGER) if err != nil { @@ -747,7 +747,7 @@ var runCmd = &cobra.Command{ context.Background(), conf.Plugin.Timeout) defer cancel() - clientCfg := map[string]interface{}{ + clientCfg := map[string]any{ "id": client.ID, "name": configBlockName, "group": configGroupName, @@ -804,7 +804,7 @@ var runCmd = &cobra.Command{ } // Verify that the pool is properly populated. - logger.Info().Fields(map[string]interface{}{ + logger.Info().Fields(map[string]any{ "name": configBlockName, "count": strconv.Itoa(pools[configGroupName][configBlockName].Size()), }).Msg("There are clients available in the pool") @@ -824,7 +824,7 @@ var runCmd = &cobra.Command{ _, err = pluginRegistry.Run( pluginTimeoutCtx, - map[string]interface{}{"name": configBlockName, "size": currentPoolSize}, + map[string]any{"name": configBlockName, "size": currentPoolSize}, v1.HookName_HOOK_NAME_ON_NEW_POOL) if err != nil { logger.Error().Err(err).Msg("Failed to run OnNewPool hooks") @@ -876,7 +876,7 @@ var runCmd = &cobra.Command{ context.Background(), conf.Plugin.Timeout) defer cancel() - if data, ok := conf.GlobalKoanf.Get("proxies").(map[string]interface{}); ok { + if data, ok := conf.GlobalKoanf.Get("proxies").(map[string]any); ok { _, err = pluginRegistry.Run( pluginTimeoutCtx, data, v1.HookName_HOOK_NAME_ON_NEW_PROXY) if err != nil { @@ -947,7 +947,7 @@ var runCmd = &cobra.Command{ context.Background(), conf.Plugin.Timeout) defer cancel() - if data, ok := conf.GlobalKoanf.Get("servers").(map[string]interface{}); ok { + if data, ok := conf.GlobalKoanf.Get("servers").(map[string]any); ok { _, err = pluginRegistry.Run( pluginTimeoutCtx, data, v1.HookName_HOOK_NAME_ON_NEW_SERVER) if err != nil { @@ -994,7 +994,7 @@ var runCmd = &cobra.Command{ go httpServer.Start() logger.Info().Fields( - map[string]interface{}{ + map[string]any{ "network": apiOptions.GRPCNetwork, "address": apiOptions.GRPCAddress, }, diff --git a/config/config.go b/config/config.go index 4247d998..9cc0584b 100644 --- a/config/config.go +++ b/config/config.go @@ -32,7 +32,7 @@ type IConfig interface { LoadGlobalConfigFile(ctx context.Context) *gerr.GatewayDError LoadPluginConfigFile(ctx context.Context) *gerr.GatewayDError MergeGlobalConfig( - ctx context.Context, updatedGlobalConfig map[string]interface{}) *gerr.GatewayDError + ctx context.Context, updatedGlobalConfig map[string]any) *gerr.GatewayDError } type Config struct { @@ -344,7 +344,7 @@ func loadEnvVars() *env.Env { // transformEnvVariable transforms the environment variable name to a format based on JSON tags. func transformEnvVariable(envVar string) string { - structs := []interface{}{ + structs := []any{ &API{}, &Logger{}, &Pool{}, @@ -444,7 +444,7 @@ func (c *Config) UnmarshalPluginConfig(ctx context.Context) *gerr.GatewayDError } func (c *Config) MergeGlobalConfig( - ctx context.Context, updatedGlobalConfig map[string]interface{}, + ctx context.Context, updatedGlobalConfig map[string]any, ) *gerr.GatewayDError { _, span := otel.Tracer(TracerName).Start(ctx, "Merge global config from plugins") @@ -530,7 +530,7 @@ func (c *Config) ConvertKeysToLowercase(ctx context.Context) *gerr.GatewayDError globalConfig.Servers = convertMapKeysToLowercase(globalConfig.Servers) globalConfig.Metrics = convertMapKeysToLowercase(globalConfig.Metrics) - // Convert the globalConfig back to a map[string]interface{} + // Convert the globalConfig back to a map[string]any configMap, err := structToMap(globalConfig) if err != nil { span.RecordError(err) @@ -554,9 +554,9 @@ func (c *Config) ConvertKeysToLowercase(ctx context.Context) *gerr.GatewayDError return nil } -// structToMap converts a given struct to a map[string]interface{}. -func structToMap(v interface{}) (map[string]interface{}, error) { - var result map[string]interface{} +// structToMap converts a given struct to a map[string]any. +func structToMap(v any) (map[string]any, error) { + var result map[string]any data, err := json.Marshal(v) if err != nil { return nil, fmt.Errorf("failed to marshal struct: %w", err) @@ -785,7 +785,7 @@ func (c *Config) ValidateGlobalConfig(ctx context.Context) *gerr.GatewayDError { } // generateTagMapping generates a map of JSON tags to lower case json tags. -func generateTagMapping(structs []interface{}, tagMapping map[string]string) { +func generateTagMapping(structs []any, tagMapping map[string]string) { for _, s := range structs { structValue := reflect.ValueOf(s).Elem() structType := structValue.Type() @@ -796,7 +796,7 @@ func generateTagMapping(structs []interface{}, tagMapping map[string]string) { // Handle nested structs if field.Type.Kind() == reflect.Struct { - generateTagMapping([]interface{}{fieldValue.Addr().Interface()}, tagMapping) + generateTagMapping([]any{fieldValue.Addr().Interface()}, tagMapping) } jsonTag := field.Tag.Get("json") diff --git a/config/config_test.go b/config/config_test.go index aa8176c6..28487e25 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -131,9 +131,9 @@ func TestMergeGlobalConfig(t *testing.T) { assert.Equal(t, DefaultLogLevel, config.Global.Loggers[Default].Level) // Merge a config that sets the log level to debug. - err = config.MergeGlobalConfig(ctx, map[string]interface{}{ - "loggers": map[string]interface{}{ - "default": map[string]interface{}{ + err = config.MergeGlobalConfig(ctx, map[string]any{ + "loggers": map[string]any{ + "default": map[string]any{ "level": "debug", }, }, diff --git a/logging/hclog_adapter.go b/logging/hclog_adapter.go index 027ae925..16fad1cd 100644 --- a/logging/hclog_adapter.go +++ b/logging/hclog_adapter.go @@ -19,10 +19,10 @@ type HcLogAdapter struct { logger *zerolog.Logger name string - impliedArgs []interface{} + impliedArgs []any } -func (h HcLogAdapter) Log(level hclog.Level, msg string, args ...interface{}) { +func (h HcLogAdapter) Log(level hclog.Level, msg string, args ...any) { switch level { case hclog.Off: return @@ -41,31 +41,31 @@ func (h HcLogAdapter) Log(level hclog.Level, msg string, args ...interface{}) { } } -func (h HcLogAdapter) Trace(msg string, args ...interface{}) { +func (h HcLogAdapter) Trace(msg string, args ...any) { extraArgs := ToMap(args) extraArgs["plugin"] = h.name h.logger.Trace().Fields(extraArgs).Msg(msg) } -func (h HcLogAdapter) Debug(msg string, args ...interface{}) { +func (h HcLogAdapter) Debug(msg string, args ...any) { extraArgs := ToMap(args) extraArgs["plugin"] = h.name h.logger.Debug().Fields(extraArgs).Msg(msg) } -func (h HcLogAdapter) Info(msg string, args ...interface{}) { +func (h HcLogAdapter) Info(msg string, args ...any) { extraArgs := ToMap(args) extraArgs["plugin"] = h.name h.logger.Info().Fields(extraArgs).Msg(msg) } -func (h HcLogAdapter) Warn(msg string, args ...interface{}) { +func (h HcLogAdapter) Warn(msg string, args ...any) { extraArgs := ToMap(args) extraArgs["plugin"] = h.name h.logger.Warn().Fields(extraArgs).Msg(msg) } -func (h HcLogAdapter) Error(msg string, args ...interface{}) { +func (h HcLogAdapter) Error(msg string, args ...any) { extraArgs := ToMap(args) extraArgs["plugin"] = h.name h.logger.Error().Fields(extraArgs).Msg(msg) @@ -115,12 +115,12 @@ func (h HcLogAdapter) IsError() bool { return h.logger.GetLevel() >= zerolog.ErrorLevel } -func (h HcLogAdapter) ImpliedArgs() []interface{} { +func (h HcLogAdapter) ImpliedArgs() []any { // Not supported return nil } -func (h HcLogAdapter) With(args ...interface{}) hclog.Logger { +func (h HcLogAdapter) With(args ...any) hclog.Logger { logger := h.logger.With().Fields(ToMap(args)).Logger() return NewHcLogAdapter(&logger, h.Name()) } @@ -179,8 +179,8 @@ func convertLevel(level hclog.Level) zerolog.Level { return zerolog.NoLevel } -func ToMap(keyValues []interface{}) map[string]interface{} { - mapped := map[string]interface{}{} +func ToMap(keyValues []any) map[string]any { + mapped := map[string]any{} if len(keyValues) == 0 { return mapped @@ -197,7 +197,7 @@ func ToMap(keyValues []interface{}) map[string]interface{} { return mapped } -func merge(mapped map[string]interface{}, key, value interface{}) { +func merge(mapped map[string]any, key, value any) { var casted string switch castedKey := key.(type) { diff --git a/metrics/merger.go b/metrics/merger.go index 33c06364..b07bc58c 100644 --- a/metrics/merger.go +++ b/metrics/merger.go @@ -70,7 +70,7 @@ func (m *Merger) Add(pluginName string, unixDomainSocket string) { if _, ok := m.Addresses[pluginName]; ok { m.Logger.Warn().Fields( - map[string]interface{}{ + map[string]any{ "plugin": pluginName, "socket": unixDomainSocket, }).Msg("Plugin already registered, skipping") @@ -87,7 +87,7 @@ func (m *Merger) Remove(pluginName string) { if _, ok := m.Addresses[pluginName]; !ok { m.Logger.Warn().Fields( - map[string]interface{}{ + map[string]any{ "plugin": pluginName, }).Msg("Plugin not registered, skipping") return @@ -202,7 +202,7 @@ func (m *Merger) MergeMetrics(pluginMetrics map[string][]byte) *gerr.GatewayDErr } m.Logger.Trace().Fields( - map[string]interface{}{ + map[string]any{ "plugin": pluginName, "count": len(metricNames), }).Msgf("Processed and merged metrics") @@ -256,7 +256,7 @@ func (m *Merger) Start() { if len(m.Addresses) > 0 { m.scheduler.StartAsync() m.Logger.Info().Fields( - map[string]interface{}{ + map[string]any{ "startDelay": startDelay.Format(time.RFC3339), "metricsMergerPeriod": m.MetricsMergerPeriod.String(), }, diff --git a/network/client.go b/network/client.go index 6d8a2537..bc6ff5a2 100644 --- a/network/client.go +++ b/network/client.go @@ -204,7 +204,7 @@ func (c *Client) Send(data []byte) (int, *gerr.GatewayDError) { } c.logger.Debug().Fields( - map[string]interface{}{ + map[string]any{ "length": sent, "address": c.Address, }, @@ -364,7 +364,7 @@ func (c *Client) IsConnected() bool { if c.conn == nil || c.ID == "" { c.logger.Debug().Fields( - map[string]interface{}{ + map[string]any{ "address": c.Address, "reason": "connection is nil or invalid", }).Msg("Connection to server is closed") diff --git a/network/proxy.go b/network/proxy.go index aa9971c7..50ad47b4 100644 --- a/network/proxy.go +++ b/network/proxy.go @@ -87,7 +87,7 @@ func NewProxy( func() { now := time.Now() proxy.Logger.Trace().Msg("Running the client health check to recycle connection(s).") - proxy.AvailableConnections.ForEach(func(_, value interface{}) bool { + proxy.AvailableConnections.ForEach(func(_, value any) bool { if client, ok := value.(*Client); ok { // Connection is probably dead by now. proxy.AvailableConnections.Remove(client.ID) @@ -135,7 +135,7 @@ func NewProxy( // Start the scheduler. proxy.scheduler.StartAsync() proxy.Logger.Info().Fields( - map[string]interface{}{ + map[string]any{ "startDelay": startDelay.Format(time.RFC3339), "healthCheckPeriod": proxy.HealthCheckPeriod.String(), }, @@ -160,7 +160,7 @@ func (pr *Proxy) Connect(conn *ConnWrapper) *gerr.GatewayDError { var clientID string // Get the first available client from the pool. - pr.AvailableConnections.ForEach(func(key, _ interface{}) bool { + pr.AvailableConnections.ForEach(func(key, _ any) bool { if cid, ok := key.(string); ok { clientID = cid return false // stop the loop. @@ -193,7 +193,7 @@ func (pr *Proxy) Connect(conn *ConnWrapper) *gerr.GatewayDError { metrics.ProxiedConnections.WithLabelValues(pr.GetGroupName(), pr.GetBlockName()).Inc() - fields := map[string]interface{}{ + fields := map[string]any{ "function": "proxy.connect", "client": "unknown", "server": RemoteAddr(conn.Conn()), @@ -204,13 +204,13 @@ func (pr *Proxy) Connect(conn *ConnWrapper) *gerr.GatewayDError { pr.Logger.Debug().Fields(fields).Msg("Client has been assigned") pr.Logger.Debug().Fields( - map[string]interface{}{ + map[string]any{ "function": "proxy.connect", "count": pr.AvailableConnections.Size(), }, ).Msg("Available client connections") pr.Logger.Debug().Fields( - map[string]interface{}{ + map[string]any{ "function": "proxy.connect", "count": pr.busyConnections.Size(), }, @@ -257,13 +257,13 @@ func (pr *Proxy) Disconnect(conn *ConnWrapper) *gerr.GatewayDError { metrics.ProxiedConnections.WithLabelValues(pr.GetGroupName(), pr.GetBlockName()).Dec() pr.Logger.Debug().Fields( - map[string]interface{}{ + map[string]any{ "function": "proxy.disconnect", "count": pr.AvailableConnections.Size(), }, ).Msg("Available client connections") pr.Logger.Debug().Fields( - map[string]interface{}{ + map[string]any{ "function": "proxy.disconnect", "count": pr.busyConnections.Size(), }, @@ -342,7 +342,7 @@ func (pr *Proxy) PassThroughToServer(conn *ConnWrapper, stack *Stack) *gerr.Gate span.RecordError(err) } else { pr.Logger.Debug().Fields( - map[string]interface{}{ + map[string]any{ "function": "upgradeToTLS", "local": LocalAddr(conn.Conn()), "remote": RemoteAddr(conn.Conn()), @@ -358,7 +358,7 @@ func (pr *Proxy) PassThroughToServer(conn *ConnWrapper, stack *Stack) *gerr.Gate // Check if the TLS handshake was successful. if conn.IsTLSEnabled() { pr.Logger.Debug().Fields( - map[string]interface{}{ + map[string]any{ "local": LocalAddr(conn.Conn()), "remote": RemoteAddr(conn.Conn()), }, @@ -367,7 +367,7 @@ func (pr *Proxy) PassThroughToServer(conn *ConnWrapper, stack *Stack) *gerr.Gate metrics.TLSConnections.WithLabelValues(pr.GetGroupName(), pr.GetBlockName()).Inc() } else { pr.Logger.Error().Fields( - map[string]interface{}{ + map[string]any{ "local": LocalAddr(conn.Conn()), "remote": RemoteAddr(conn.Conn()), }, @@ -382,7 +382,7 @@ func (pr *Proxy) PassThroughToServer(conn *ConnWrapper, stack *Stack) *gerr.Gate // Client sent a SSL request, but the server does not support SSL. pr.Logger.Warn().Fields( - map[string]interface{}{ + map[string]any{ "local": LocalAddr(conn.Conn()), "remote": RemoteAddr(conn.Conn()), }, @@ -409,7 +409,7 @@ func (pr *Proxy) PassThroughToServer(conn *ConnWrapper, stack *Stack) *gerr.Gate if terminate, resp := pr.shouldTerminate(result); terminate { if resp != nil { pr.Logger.Trace().Fields( - map[string]interface{}{ + map[string]any{ "function": "proxy.passthrough", "result": resp, }, @@ -515,7 +515,7 @@ func (pr *Proxy) PassThroughToClient(conn *ConnWrapper, stack *Stack) *gerr.Gate // If there is an error, close the ingress connection. if err != nil { - fields := map[string]interface{}{"function": "proxy.passthrough"} + fields := map[string]any{"function": "proxy.passthrough"} if client.LocalAddr() != "" { fields["localAddr"] = client.LocalAddr() } @@ -643,7 +643,7 @@ func (pr *Proxy) Shutdown() { _, span := otel.Tracer(config.TracerName).Start(pr.ctx, "Shutdown") defer span.End() - pr.AvailableConnections.ForEach(func(_, value interface{}) bool { + pr.AvailableConnections.ForEach(func(_, value any) bool { if client, ok := value.(*Client); ok { if client.IsConnected() { client.Close() @@ -654,7 +654,7 @@ func (pr *Proxy) Shutdown() { pr.AvailableConnections.Clear() pr.Logger.Debug().Msg("All available connections have been closed") - pr.busyConnections.ForEach(func(key, value interface{}) bool { + pr.busyConnections.ForEach(func(key, value any) bool { if conn, ok := key.(net.Conn); ok { // This will stop all the Conn.Read() and Conn.Write() calls. if err := conn.SetDeadline(time.Now()); err != nil { @@ -686,7 +686,7 @@ func (pr *Proxy) AvailableConnectionsString() []string { defer span.End() connections := make([]string, 0) - pr.AvailableConnections.ForEach(func(_, value interface{}) bool { + pr.AvailableConnections.ForEach(func(_, value any) bool { if cl, ok := value.(*Client); ok { connections = append(connections, cl.LocalAddr()) } @@ -702,7 +702,7 @@ func (pr *Proxy) BusyConnectionsString() []string { defer span.End() connections := make([]string, 0) - pr.busyConnections.ForEach(func(key, _ interface{}) bool { + pr.busyConnections.ForEach(func(key, _ any) bool { if conn, ok := key.(*ConnWrapper); ok { connections = append(connections, RemoteAddr(conn.Conn())) } @@ -745,7 +745,7 @@ func (pr *Proxy) receiveTrafficFromClient(conn net.Conn) ([]byte, *gerr.GatewayD } pr.Logger.Debug().Fields( - map[string]interface{}{ + map[string]any{ "length": total, "local": LocalAddr(conn), "remote": RemoteAddr(conn), @@ -777,7 +777,7 @@ func (pr *Proxy) sendTrafficToServer(client *Client, request []byte) (int, *gerr span.RecordError(err) } pr.Logger.Debug().Fields( - map[string]interface{}{ + map[string]any{ "function": "proxy.passthrough", "length": sent, "local": client.LocalAddr(), @@ -801,7 +801,7 @@ func (pr *Proxy) receiveTrafficFromServer(client *Client) (int, []byte, *gerr.Ga // Receive the response from the server. received, response, err := client.Receive() - fields := map[string]interface{}{ + fields := map[string]any{ "function": "proxy.passthrough", "length": received, } @@ -847,7 +847,7 @@ func (pr *Proxy) sendTrafficToClient( } pr.Logger.Debug().Fields( - map[string]interface{}{ + map[string]any{ "function": "proxy.passthrough", "length": sent, "local": LocalAddr(conn), @@ -865,7 +865,7 @@ func (pr *Proxy) sendTrafficToClient( // shouldTerminate is a function that retrieves the terminate field from the hook result. // Only the OnTrafficFromClient hook will terminate the request. -func (pr *Proxy) shouldTerminate(result map[string]interface{}) (bool, map[string]interface{}) { +func (pr *Proxy) shouldTerminate(result map[string]any) (bool, map[string]any) { _, span := otel.Tracer(config.TracerName).Start(pr.ctx, "shouldTerminate") defer span.End() @@ -884,7 +884,7 @@ func (pr *Proxy) shouldTerminate(result map[string]interface{}) (bool, map[strin // that is the `__terminal__` field is set in one of the outputs. keys := maps.Keys(result) terminate := slices.Contains(keys, sdkAct.Terminal) && cast.ToBool(result[sdkAct.Terminal]) - actionResult := make(map[string]interface{}) + actionResult := make(map[string]any) for _, output := range outputs { if !cast.ToBool(output.Verdict) { pr.Logger.Debug().Msg( @@ -899,13 +899,13 @@ func (pr *Proxy) shouldTerminate(result map[string]interface{}) (bool, map[strin pr.Logger.Error().Err(err).Msg("Error running policy") } // The terminate action should return a map. - if v, ok := actRes.(map[string]interface{}); ok { + if v, ok := actRes.(map[string]any); ok { actionResult = v } } if terminate { pr.Logger.Debug().Fields( - map[string]interface{}{ + map[string]any{ "function": "proxy.passthrough", "reason": "terminate", }, @@ -916,7 +916,7 @@ func (pr *Proxy) shouldTerminate(result map[string]interface{}) (bool, map[strin // getPluginModifiedRequest is a function that retrieves the modified request // from the hook result. -func (pr *Proxy) getPluginModifiedRequest(result map[string]interface{}) []byte { +func (pr *Proxy) getPluginModifiedRequest(result map[string]any) []byte { _, span := otel.Tracer(config.TracerName).Start(pr.ctx, "getPluginModifiedRequest") defer span.End() @@ -932,7 +932,7 @@ func (pr *Proxy) getPluginModifiedRequest(result map[string]interface{}) []byte // getPluginModifiedResponse is a function that retrieves the modified response // from the hook result. -func (pr *Proxy) getPluginModifiedResponse(result map[string]interface{}) ([]byte, int) { +func (pr *Proxy) getPluginModifiedResponse(result map[string]any) ([]byte, int) { _, span := otel.Tracer(config.TracerName).Start(pr.ctx, "getPluginModifiedResponse") defer span.End() @@ -949,7 +949,7 @@ func (pr *Proxy) getPluginModifiedResponse(result map[string]interface{}) ([]byt func (pr *Proxy) isConnectionHealthy(conn net.Conn) bool { if n, err := conn.Read([]byte{}); n == 0 && err != nil { pr.Logger.Debug().Fields( - map[string]interface{}{ + map[string]any{ "remote": RemoteAddr(conn), "local": LocalAddr(conn), "reason": "read 0 bytes", diff --git a/network/retry.go b/network/retry.go index 1d206777..c9ea87c6 100644 --- a/network/retry.go +++ b/network/retry.go @@ -78,7 +78,7 @@ func (r *Retry) Retry(callback RetryCallback) (any, error) { if retry > 0 { r.Logger.Debug().Fields( - map[string]interface{}{ + map[string]any{ "retry": retry, "delay": backoffDuration.String(), }, diff --git a/network/server.go b/network/server.go index 0858976c..60af37ac 100644 --- a/network/server.go +++ b/network/server.go @@ -100,7 +100,7 @@ func (s *Server) OnBoot() Action { // Run the OnBooting hooks. _, err := s.PluginRegistry.Run( pluginTimeoutCtx, - map[string]interface{}{"status": fmt.Sprint(s.Status)}, + map[string]any{"status": fmt.Sprint(s.Status)}, v1.HookName_HOOK_NAME_ON_BOOTING) if err != nil { s.Logger.Error().Err(err).Msg("Failed to run OnBooting hook") @@ -119,7 +119,7 @@ func (s *Server) OnBoot() Action { _, err = s.PluginRegistry.Run( pluginTimeoutCtx, - map[string]interface{}{"status": fmt.Sprint(s.Status)}, + map[string]any{"status": fmt.Sprint(s.Status)}, v1.HookName_HOOK_NAME_ON_BOOTED) if err != nil { s.Logger.Error().Err(err).Msg("Failed to run OnBooted hook") @@ -144,8 +144,8 @@ func (s *Server) OnOpen(conn *ConnWrapper) ([]byte, Action) { pluginTimeoutCtx, cancel := context.WithTimeout(context.Background(), s.PluginTimeout) defer cancel() // Run the OnOpening hooks. - onOpeningData := map[string]interface{}{ - "client": map[string]interface{}{ + onOpeningData := map[string]any{ + "client": map[string]any{ "local": LocalAddr(conn.Conn()), "remote": RemoteAddr(conn.Conn()), }, @@ -189,8 +189,8 @@ func (s *Server) OnOpen(conn *ConnWrapper) ([]byte, Action) { pluginTimeoutCtx, cancel = context.WithTimeout(context.Background(), s.PluginTimeout) defer cancel() - onOpenedData := map[string]interface{}{ - "client": map[string]interface{}{ + onOpenedData := map[string]any{ + "client": map[string]any{ "local": LocalAddr(conn.Conn()), "remote": RemoteAddr(conn.Conn()), }, @@ -221,8 +221,8 @@ func (s *Server) OnClose(conn *ConnWrapper, err error) Action { pluginTimeoutCtx, cancel := context.WithTimeout(context.Background(), s.PluginTimeout) defer cancel() - data := map[string]interface{}{ - "client": map[string]interface{}{ + data := map[string]any{ + "client": map[string]any{ "local": LocalAddr(conn.Conn()), "remote": RemoteAddr(conn.Conn()), }, @@ -281,8 +281,8 @@ func (s *Server) OnClose(conn *ConnWrapper, err error) Action { pluginTimeoutCtx, cancel = context.WithTimeout(context.Background(), s.PluginTimeout) defer cancel() - data = map[string]interface{}{ - "client": map[string]interface{}{ + data = map[string]any{ + "client": map[string]any{ "local": LocalAddr(conn.Conn()), "remote": RemoteAddr(conn.Conn()), }, @@ -314,8 +314,8 @@ func (s *Server) OnTraffic(conn *ConnWrapper, stopConnection chan struct{}) Acti pluginTimeoutCtx, cancel := context.WithTimeout(context.Background(), s.PluginTimeout) defer cancel() - onTrafficData := map[string]interface{}{ - "client": map[string]interface{}{ + onTrafficData := map[string]any{ + "client": map[string]any{ "local": LocalAddr(conn.Conn()), "remote": RemoteAddr(conn.Conn()), }, @@ -393,7 +393,7 @@ func (s *Server) OnShutdown() { // Run the OnShutdown hooks. _, err := s.PluginRegistry.Run( pluginTimeoutCtx, - map[string]interface{}{"connections": s.CountConnections()}, + map[string]any{"connections": s.CountConnections()}, v1.HookName_HOOK_NAME_ON_SHUTDOWN) if err != nil { s.Logger.Error().Err(err).Msg("Failed to run OnShutdown hook") @@ -426,7 +426,7 @@ func (s *Server) OnTick() (time.Duration, Action) { // Run the OnTick hooks. _, err := s.PluginRegistry.Run( pluginTimeoutCtx, - map[string]interface{}{"connections": s.CountConnections()}, + map[string]any{"connections": s.CountConnections()}, v1.HookName_HOOK_NAME_ON_TICK) if err != nil { s.Logger.Error().Err(err).Msg("Failed to run OnTick hook") @@ -461,7 +461,7 @@ func (s *Server) Run() *gerr.GatewayDError { defer cancel() // Run the OnRun hooks. // Since Run is blocking, we need to run OnRun before it. - onRunData := map[string]interface{}{"address": addr} + onRunData := map[string]any{"address": addr} if err != nil && err.Unwrap() != nil { onRunData["error"] = err.OriginalError.Error() } diff --git a/network/utils.go b/network/utils.go index 0d7e0bab..7e32af83 100644 --- a/network/utils.go +++ b/network/utils.go @@ -52,18 +52,18 @@ func trafficData( conn net.Conn, client *Client, fields []Field, - err interface{}, -) map[string]interface{} { + err any, +) map[string]any { if conn == nil || client == nil { return nil } - data := map[string]interface{}{ - "client": map[string]interface{}{ + data := map[string]any{ + "client": map[string]any{ "local": LocalAddr(conn), "remote": RemoteAddr(conn), }, - "server": map[string]interface{}{ + "server": map[string]any{ "local": client.LocalAddr(), "remote": client.RemoteAddr(), }, @@ -90,7 +90,7 @@ func trafficData( } // extractFieldValue extracts the given field name and error message from the result of the hook. -func extractFieldValue(result map[string]interface{}, fieldName string) ([]byte, string) { +func extractFieldValue(result map[string]any, fieldName string) ([]byte, string) { var data []byte var err string diff --git a/network/utils_test.go b/network/utils_test.go index 1238cbea..90366052 100644 --- a/network/utils_test.go +++ b/network/utils_test.go @@ -165,7 +165,7 @@ func BenchmarkTrafficData(b *testing.B) { func BenchmarkExtractFieldValue(b *testing.B) { for i := 0; i < b.N; i++ { extractFieldValue( - map[string]interface{}{ + map[string]any{ "test": "test", }, "test", diff --git a/plugin/.template/project/{{ plugin_name }}/plugin/module.go b/plugin/.template/project/{{ plugin_name }}/plugin/module.go index 2ff76065..add286d0 100644 --- a/plugin/.template/project/{{ plugin_name }}/plugin/module.go +++ b/plugin/.template/project/{{ plugin_name }}/plugin/module.go @@ -17,26 +17,26 @@ var ( } // TODO: Handle this in a better way // https://github.com/gatewayd-io/gatewayd-plugin-sdk/issues/3 - PluginConfig = map[string]interface{}{ - "id": map[string]interface{}{ + PluginConfig = map[string]any{ + "id": map[string]any{ "{{ plugin_name }}": PluginID.GetName(), "version": PluginID.GetVersion(), "remoteUrl": PluginID.GetRemoteUrl(), }, "description": "Template plugin", - "authors": []interface{}{ + "authors": []any{ {% if authors %}"{{ authors|join:'", "'|safe }}",{% endif %} }, "license": "Apache 2.0", "projectUrl": "{{ remote_url }}", // Compile-time configuration - "config": map[string]interface{}{ + "config": map[string]any{ "metricsEnabled": sdkConfig.GetEnv("METRICS_ENABLED", "true"), "metricsUnixDomainSocket": sdkConfig.GetEnv( "METRICS_UNIX_DOMAIN_SOCKET", "/tmp/{{ plugin_name }}.sock"), "metricsEndpoint": sdkConfig.GetEnv("METRICS_ENDPOINT", "/metrics"), }, - "hooks": []interface{}{ + "hooks": []any{ // Converting HookName to int32 is required because the plugin // framework doesn't support enums. See: // https://github.com/gatewayd-io/gatewayd-plugin-sdk/issues/3 @@ -66,7 +66,7 @@ var ( // to remove it in your plugin. int32(v1.HookName(1000)), }, - "tags": []interface{}{"template", "plugin"}, - "categories": []interface{}{"template"}, + "tags": []any{"template", "plugin"}, + "categories": []any{"template"}, } ) diff --git a/plugin/.template/project/{{ plugin_name }}/plugin/plugin.go b/plugin/.template/project/{{ plugin_name }}/plugin/plugin.go index c6550ca6..47226e41 100644 --- a/plugin/.template/project/{{ plugin_name }}/plugin/plugin.go +++ b/plugin/.template/project/{{ plugin_name }}/plugin/plugin.go @@ -27,7 +27,7 @@ func (p *{{ pascal_case_plugin_name }}) GRPCServer(b *goplugin.GRPCBroker, s *gr } // GRPCClient returns the plugin client. -func (p *{{ pascal_case_plugin_name }}) GRPCClient(ctx context.Context, b *goplugin.GRPCBroker, c *grpc.ClientConn) (interface{}, error) { +func (p *{{ pascal_case_plugin_name }}) GRPCClient(ctx context.Context, b *goplugin.GRPCBroker, c *grpc.ClientConn) (any, error) { return v1.NewGatewayDPluginServiceClient(c), nil } diff --git a/plugin/plugin_registry.go b/plugin/plugin_registry.go index b5130d52..0586dc48 100644 --- a/plugin/plugin_registry.go +++ b/plugin/plugin_registry.go @@ -121,7 +121,7 @@ func (reg *Registry) List() []sdkPlugin.Identifier { defer span.End() var plugins []sdkPlugin.Identifier - reg.plugins.ForEach(func(key, _ interface{}) bool { + reg.plugins.ForEach(func(key, _ any) bool { if id, ok := key.(sdkPlugin.Identifier); ok { plugins = append(plugins, id) } @@ -180,7 +180,7 @@ func (reg *Registry) ForEach(function func(sdkPlugin.Identifier, *Plugin)) { _, span := otel.Tracer(config.TracerName).Start(reg.ctx, "ForEach") defer span.End() - reg.plugins.ForEach(func(key, value interface{}) bool { + reg.plugins.ForEach(func(key, value any) bool { if id, ok := key.(sdkPlugin.Identifier); ok { if plugin, ok := value.(*Plugin); ok { function(id, plugin) @@ -207,7 +207,7 @@ func (reg *Registry) Shutdown() { _, span := otel.Tracer(config.TracerName).Start(reg.ctx, "Shutdown") defer span.End() - reg.plugins.ForEach(func(key, value interface{}) bool { + reg.plugins.ForEach(func(key, value any) bool { if id, ok := key.(sdkPlugin.Identifier); ok { if plugin, ok := value.(*Plugin); ok { plugin.Stop() diff --git a/plugin/plugin_registry_test.go b/plugin/plugin_registry_test.go index fcd66294..67996b60 100644 --- a/plugin/plugin_registry_test.go +++ b/plugin/plugin_registry_test.go @@ -129,7 +129,7 @@ func Test_PluginRegistry_Run(t *testing.T) { ) (*v1.Struct, error) { return args, nil }) - result, err := reg.Run(context.Background(), map[string]interface{}{}, v1.HookName_HOOK_NAME_ON_NEW_LOGGER) + result, err := reg.Run(context.Background(), map[string]any{}, v1.HookName_HOOK_NAME_ON_NEW_LOGGER) assert.NotNil(t, result) assert.Nil(t, err) } @@ -177,7 +177,7 @@ func BenchmarkHookRun(b *testing.B) { //nolint:errcheck reg.Run( context.Background(), - map[string]interface{}{ + map[string]any{ "test": "test", }, v1.HookName_HOOK_NAME_ON_NEW_LOGGER, diff --git a/plugin/plugin_scaffold.go b/plugin/plugin_scaffold.go index 808fb6c4..d99fdd65 100644 --- a/plugin/plugin_scaffold.go +++ b/plugin/plugin_scaffold.go @@ -117,14 +117,14 @@ func Scaffold(inputFile string, outputDir string) ([]string, error) { // returns a map containing the parsed data. // // This function opens the provided input file path, reads its contents, and unmarshals -// the YAML data into a Go map[string]interface{}. It returns the parsed map and any encountered error. -func readScaffoldInputFile(inputFilePath string) (map[string]interface{}, error) { +// the YAML data into a Go map[string]any. It returns the parsed map and any encountered error. +func readScaffoldInputFile(inputFilePath string) (map[string]any, error) { inputBytes, err := os.ReadFile(inputFilePath) if err != nil { return nil, gerr.ErrFailedToReadPluginScaffoldInputFile.Wrap(err) } - inputJSON := make(map[string]interface{}) + inputJSON := make(map[string]any) err = yaml.Unmarshal(inputBytes, &inputJSON) if err != nil { return nil, gerr.ErrFailedToReadPluginScaffoldInputFile.Wrap(err) diff --git a/plugin/utils.go b/plugin/utils.go index bb4bc87d..64713514 100644 --- a/plugin/utils.go +++ b/plugin/utils.go @@ -21,18 +21,18 @@ func NewCommand(cmd string, args []string, env []string) *exec.Cmd { // castToPrimitiveTypes casts the values of a map to its primitive type // (e.g. time.Duration to float64) to prevent structpb invalid type(s) errors. -func castToPrimitiveTypes(args map[string]interface{}) map[string]interface{} { +func castToPrimitiveTypes(args map[string]any) map[string]any { for key, value := range args { switch value := value.(type) { case time.Duration: // Cast time.Duration to string. args[key] = value.String() - case map[string]interface{}: + case map[string]any: // Recursively cast nested maps. args[key] = castToPrimitiveTypes(value) - case []interface{}: + case []any: // Recursively cast nested arrays. - array := make([]interface{}, len(value)) + array := make([]any, len(value)) for idx, v := range value { if durVal, ok := v.(time.Duration); ok { // Cast time.Duration to string. @@ -92,7 +92,7 @@ func applyPolicies( } logger.Debug().Fields( - map[string]interface{}{ + map[string]any{ "hook": hook.Name, "signals": signalNames, }, @@ -100,7 +100,7 @@ func applyPolicies( outputs := reg.Apply(signals, hook) logger.Debug().Fields( - map[string]interface{}{ + map[string]any{ "hook": hook.Name, "outputs": outputs, }, diff --git a/plugin/utils_test.go b/plugin/utils_test.go index 68e573e8..0ff86be7 100644 --- a/plugin/utils_test.go +++ b/plugin/utils_test.go @@ -23,33 +23,33 @@ func Test_NewCommand(t *testing.T) { // Test_castToPrimitiveTypes tests the CastToPrimitiveTypes function. func Test_castToPrimitiveTypes(t *testing.T) { - actual := map[string]interface{}{ + actual := map[string]any{ "string": "test", "int": 123, "bool": true, - "map": map[string]interface{}{"test": "test"}, + "map": map[string]any{"test": "test"}, "duration": time.Duration(123), - "array": []interface{}{ + "array": []any{ "test", 123, true, - map[string]interface{}{ + map[string]any{ "test": "test", }, time.Duration(123), }, } - expected := map[string]interface{}{ + expected := map[string]any{ "string": "test", "int": 123, "bool": true, - "map": map[string]interface{}{"test": "test"}, + "map": map[string]any{"test": "test"}, "duration": "123ns", // time.Duration is cast to string. - "array": []interface{}{ + "array": []any{ "test", 123, true, - map[string]interface{}{ + map[string]any{ "test": "test", }, "123ns", // time.Duration is cast to string. @@ -62,7 +62,7 @@ func Test_castToPrimitiveTypes(t *testing.T) { // Test_getSignals tests the getSignals function. func Test_getSignals(t *testing.T) { - result := map[string]interface{}{ + result := map[string]any{ sdkAct.Signals: []any{ (&sdkAct.Signal{ Name: "test", @@ -81,7 +81,7 @@ func Test_getSignals(t *testing.T) { // Test_getSignals_empty tests the getSignals function with an empty result. func Test_getSignals_empty(t *testing.T) { - result := map[string]interface{}{} + result := map[string]any{} signals := getSignals(result) assert.Len(t, signals, 0) } diff --git a/pool/pool.go b/pool/pool.go index 4e70087f..0860da74 100644 --- a/pool/pool.go +++ b/pool/pool.go @@ -9,16 +9,16 @@ import ( "go.opentelemetry.io/otel" ) -type Callback func(key, value interface{}) bool +type Callback func(key, value any) bool type IPool interface { ForEach(cb Callback) Pool() *sync.Map - Put(key, value interface{}) *gerr.GatewayDError - Get(key interface{}) interface{} - GetOrPut(key, value interface{}) (interface{}, bool, *gerr.GatewayDError) - Pop(key interface{}) interface{} - Remove(key interface{}) + Put(key, value any) *gerr.GatewayDError + Get(key any) any + GetOrPut(key, value any) (any, bool, *gerr.GatewayDError) + Pop(key any) any + Remove(key any) Size() int Clear() Cap() int @@ -50,7 +50,7 @@ func (p *Pool) Pool() *sync.Map { } // Put adds a new key/value pair to the pool. -func (p *Pool) Put(key, value interface{}) *gerr.GatewayDError { +func (p *Pool) Put(key, value any) *gerr.GatewayDError { _, span := otel.Tracer(config.TracerName).Start(p.ctx, "Put") defer span.End() if p.cap > 0 && p.Size() >= p.cap { @@ -68,7 +68,7 @@ func (p *Pool) Put(key, value interface{}) *gerr.GatewayDError { } // Get returns the value for the given key. -func (p *Pool) Get(key interface{}) interface{} { +func (p *Pool) Get(key any) any { _, span := otel.Tracer(config.TracerName).Start(p.ctx, "Get") defer span.End() if value, ok := p.pool.Load(key); ok { @@ -79,7 +79,7 @@ func (p *Pool) Get(key interface{}) interface{} { // GetOrPut returns the value for the given key if it exists, otherwise it adds // the key/value pair to the pool. -func (p *Pool) GetOrPut(key, value interface{}) (interface{}, bool, *gerr.GatewayDError) { +func (p *Pool) GetOrPut(key, value any) (any, bool, *gerr.GatewayDError) { _, span := otel.Tracer(config.TracerName).Start(p.ctx, "GetOrPut") defer span.End() if p.cap > 0 && p.Size() >= p.cap { @@ -97,7 +97,7 @@ func (p *Pool) GetOrPut(key, value interface{}) (interface{}, bool, *gerr.Gatewa } // Pop removes the key/value pair from the pool and returns the value. -func (p *Pool) Pop(key interface{}) interface{} { +func (p *Pool) Pop(key any) any { _, span := otel.Tracer(config.TracerName).Start(p.ctx, "Pop") defer span.End() if p.Size() == 0 { @@ -110,7 +110,7 @@ func (p *Pool) Pop(key interface{}) interface{} { } // Remove removes the key/value pair from the pool. -func (p *Pool) Remove(key interface{}) { +func (p *Pool) Remove(key any) { _, span := otel.Tracer(config.TracerName).Start(p.ctx, "Remove") defer span.End() if p.Size() == 0 { @@ -126,7 +126,7 @@ func (p *Pool) Size() int { _, span := otel.Tracer(config.TracerName).Start(p.ctx, "Size") defer span.End() var size int - p.pool.Range(func(_, _ interface{}) bool { + p.pool.Range(func(_, _ any) bool { size++ return true }) diff --git a/pool/pool_test.go b/pool/pool_test.go index 03529e91..1b6569f2 100644 --- a/pool/pool_test.go +++ b/pool/pool_test.go @@ -91,7 +91,7 @@ func TestPool_ForEach(t *testing.T) { err = pool.Put("client2.ID", "client2") assert.Nil(t, err) assert.Equal(t, 2, pool.Size()) - pool.ForEach(func(_, value interface{}) bool { + pool.ForEach(func(_, value any) bool { if c, ok := value.(string); ok { assert.NotEmpty(t, c) } @@ -195,7 +195,7 @@ func TestPool_GetClientIDs(t *testing.T) { assert.Equal(t, 2, pool.Size()) var ids []string - pool.ForEach(func(key, _ interface{}) bool { + pool.ForEach(func(key, _ any) bool { if id, ok := key.(string); ok { ids = append(ids, id) } @@ -253,7 +253,7 @@ func BenchmarkPool_ForEach(b *testing.B) { pool.Put("client1.ID", "client1") //nolint:errcheck pool.Put("client2.ID", "client2") //nolint:errcheck for i := 0; i < b.N; i++ { - pool.ForEach(func(_, _ interface{}) bool { + pool.ForEach(func(_, _ any) bool { return true }) }