Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor interface{} to any #614

Merged
merged 1 commit into from
Oct 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion act/registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
10 changes: 5 additions & 5 deletions act/registry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
)

Expand Down
6 changes: 3 additions & 3 deletions api/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
}
Expand Down Expand Up @@ -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")
Expand All @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion api/http_server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"])
Expand Down
2 changes: 1 addition & 1 deletion cmd/configs.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
6 changes: 3 additions & 3 deletions cmd/plugin_install.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions cmd/plugin_scaffold_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")

Expand All @@ -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)
Expand Down
20 changes: 10 additions & 10 deletions cmd/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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")

Expand Down Expand Up @@ -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(),
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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")
Expand All @@ -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")
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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,
},
Expand Down
18 changes: 9 additions & 9 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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{},
Expand Down Expand Up @@ -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")

Expand Down Expand Up @@ -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)
Expand All @@ -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)
Expand Down Expand Up @@ -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()
Expand All @@ -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")
Expand Down
6 changes: 3 additions & 3 deletions config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
},
},
Expand Down
Loading