Skip to content

Commit

Permalink
refactor: replace interface{} with any
Browse files Browse the repository at this point in the history
Signed-off-by: Praveen Yadav <pyadav9678@gmail.com>
  • Loading branch information
pyadav committed Feb 22, 2024
1 parent 11fd53d commit d27c8fc
Show file tree
Hide file tree
Showing 13 changed files with 30 additions and 31 deletions.
8 changes: 4 additions & 4 deletions common/cmdx/cmdx.go
Expand Up @@ -46,11 +46,11 @@ func (c *Config) File() string {
return c.filename
}

func (c *Config) Defaults(cfg interface{}) {
func (c *Config) Defaults(cfg any) {
defaults.SetDefaults(cfg)
}

func (c *Config) Init(cfg interface{}) error {
func (c *Config) Init(cfg any) error {
defaults.SetDefaults(cfg)

if fileExist(c.filename) {
Expand All @@ -65,7 +65,7 @@ func (c *Config) Read() (string, error) {
return string(cfg), err
}

func (c *Config) Write(cfg interface{}) error {
func (c *Config) Write(cfg any) error {
data, err := yaml.Marshal(cfg)
if err != nil {
return err
Expand All @@ -81,7 +81,7 @@ func (c *Config) Write(cfg interface{}) error {
return nil
}

func (c *Config) Load(cfg interface{}, opts ...ConfigLoaderOpt) error {
func (c *Config) Load(cfg any, opts ...ConfigLoaderOpt) error {
for _, opt := range opts {
opt(c)
}
Expand Down
16 changes: 8 additions & 8 deletions common/config/config.go
Expand Up @@ -85,7 +85,7 @@ func WithType(in string) LoaderOption {
// type Config struct {
// Host string `yaml:"host" cmdx:"host"`
// }
func WithBindPFlags(pfs *pflag.FlagSet, cfg interface{}) LoaderOption {
func WithBindPFlags(pfs *pflag.FlagSet, cfg any) LoaderOption {
return func(l *Loader) {
reflectedCfg := reflect.TypeOf(cfg).Elem()

Expand Down Expand Up @@ -131,15 +131,15 @@ func WithDecoderConfigOption(opts ...viper.DecoderConfigOption) LoaderOption {
}
}

// StringToJsonFunc is a mapstructure.DecodeHookFunc that converts a string to an interface{}
// StringToJsonFunc is a mapstructure.DecodeHookFunc that converts a string to an any
// if the string is valid json. This is useful for unmarshalling json strings into a map.
// For example, if you have a struct with a field of type map[string]string like labels or annotations,
func StringToJsonFunc() mapstructure.DecodeHookFunc {
return func(f, t reflect.Type, data interface{}) (interface{}, error) {
return func(f, t reflect.Type, data any) (any, error) {
// if type is string and can be parsed as json, parse it
if f.Kind() == reflect.String && t.Kind() == reflect.Map {
if f.Kind() == reflect.String && t.Kind() == reflect.Map {
var m map[string]interface{}
var m map[string]any
if err := json.Unmarshal([]byte(data.(string)), &m); err == nil {
return m, nil
}
Expand Down Expand Up @@ -172,7 +172,7 @@ func NewLoader(options ...LoaderOption) *Loader {

// Load loads configuration into the given mapstructure (https://github.com/mitchellh/mapstructure)
// from a config.yaml file and overrides with any values set in env variables
func (l *Loader) Load(config interface{}) error {
func (l *Loader) Load(config any) error {
if err := verifyParamIsPtrToStructElsePanic(config); err != nil {
return err
}
Expand Down Expand Up @@ -216,7 +216,7 @@ func (l *Loader) Load(config interface{}) error {
return nil
}

func verifyParamIsPtrToStructElsePanic(param interface{}) error {
func verifyParamIsPtrToStructElsePanic(param any) error {
value := reflect.ValueOf(param)
if value.Kind() != reflect.Ptr {
return fmt.Errorf("require ptr to a struct for Load. Got %v", value.Kind())
Expand All @@ -237,8 +237,8 @@ func getViperWithDefaults() *viper.Viper {
return v
}

func getFlattenedStructKeys(config interface{}) ([]string, error) {
var structMap map[string]interface{}
func getFlattenedStructKeys(config any) ([]string, error) {
var structMap map[string]any
if err := mapstructure.Decode(config, &structMap); err != nil {
return nil, err
}
Expand Down
2 changes: 1 addition & 1 deletion common/file/file.go
Expand Up @@ -32,7 +32,7 @@ func DirExists(path string) bool {
// in the 2nd argument
// File extension matters, only file with extension
// json, yaml, or yml that is parsable
func Parse(filePath string, v interface{}) error {
func Parse(filePath string, v any) error {
b, err := ioutil.ReadFile(filePath)
if err != nil {
return err
Expand Down
1 change: 0 additions & 1 deletion common/logger/logger.go
Expand Up @@ -125,7 +125,6 @@ func (l *connectRequestLogger) ConnectRequestf(ctx context.Context) {
Latency: durationpb.New(time.Since(requestTime)),
}),
slog.Time("time", requestTime),
slog.Any("rawHttpHeader", req.Header()),
)
l.Logger.LogAttrs(ctx, slog.LevelInfo, msg, attrs...)
}
2 changes: 1 addition & 1 deletion gateway/internal/api/v1/chatcompletions.go
Expand Up @@ -81,7 +81,7 @@ func (s *V1Handler) ChatCompletions(
return nil, errors.New(err)
}

ingesterdata := make(map[string]interface{})
ingesterdata := make(map[string]any)
providerInfo := provider.Info()

ingesterdata["provider"] = providerInfo.Name
Expand Down
2 changes: 1 addition & 1 deletion gateway/internal/api/v1/logs.go
Expand Up @@ -18,7 +18,7 @@ func (s *V1Handler) ListTrackingLogs(ctx context.Context, req *connect.Request[e

logs := []*structpb.Struct{}
for _, log := range response {
point := map[string]interface{}{
point := map[string]any{
"latency": log["latency"],
"model": log["model"],
"provider": log["provider"],
Expand Down
6 changes: 3 additions & 3 deletions gateway/internal/ingester/influx/influx.go
Expand Up @@ -32,21 +32,21 @@ func NewInfluxIngester(opts ...Option) *InfluxDBIngester {
}
}

func (in *InfluxDBIngester) Ingest(data map[string]interface{}, measurement string) {
func (in *InfluxDBIngester) Ingest(data map[string]any, measurement string) {
point := influxdb3.NewPoint(measurement, nil, data, time.Now())
err := in.client.WritePoints(context.Background(), point)
if err != nil {
in.logger.Error("Not able to ingest into db", err)
}
}

func (in *InfluxDBIngester) Get(query string) ([]map[string]interface{}, error) {
func (in *InfluxDBIngester) Get(query string) ([]map[string]any, error) {
result, err := in.client.Query(context.Background(), query)
if err != nil {
return nil, err
}

data := []map[string]interface{}{}
data := []map[string]any{}
for result.Next() {
data = append(data, result.Value())
}
Expand Down
4 changes: 2 additions & 2 deletions gateway/internal/ingester/ingester.go
@@ -1,7 +1,7 @@
package ingester

type Ingester interface {
Get(string) ([]map[string]interface{}, error)
Ingest(map[string]interface{}, string)
Get(string) ([]map[string]any, error)
Ingest(map[string]any, string)
Close() error
}
4 changes: 2 additions & 2 deletions gateway/internal/ingester/nop_ingester.go
Expand Up @@ -8,10 +8,10 @@ func NewNopIngester() *nopIngester {
return &nopIngester{}
}

func (n *nopIngester) Get(key string) ([]map[string]interface{}, error) {
func (n *nopIngester) Get(key string) ([]map[string]any, error) {
return nil, nil
}
func (n *nopIngester) Ingest(data map[string]interface{}, key string) {}
func (n *nopIngester) Ingest(data map[string]any, key string) {}

func (n *nopIngester) Close() error {
return nil
Expand Down
4 changes: 2 additions & 2 deletions gateway/internal/ratelimiter/tokenbucket_cache.go
Expand Up @@ -69,8 +69,8 @@ func (c *redisTokenBucketCache) Validate(keyname string, bucket_size int) (count
}

var ok bool
var arr []interface{}
if arr, ok = n.([]interface{}); !ok {
var arr []any
if arr, ok = n.([]any); !ok {
c.logger.Error("failed to parse redis result")
return
}
Expand Down
2 changes: 1 addition & 1 deletion gateway/models/connection.go
Expand Up @@ -40,7 +40,7 @@ func (c *Connection) MergeConfig(kv map[string]any) (err error) {
return err
}
}
if err := container.MergeFn(gabs.Wrap(c.Config), func(destination, source interface{}) interface{} {
if err := container.MergeFn(gabs.Wrap(c.Config), func(destination, source any) any {
return destination
}); err != nil {
return err
Expand Down
2 changes: 1 addition & 1 deletion gateway/pkg/cache/redis.go
Expand Up @@ -69,7 +69,7 @@ func (rc *RedisClient) Get(ctx context.Context, key string) ([]byte, error) {
return []byte(val), nil
}

func (rc *RedisClient) MGet(ctx context.Context, keys ...string) ([]interface{}, error) {
func (rc *RedisClient) MGet(ctx context.Context, keys ...string) ([]any, error) {
return rc.client.MGet(ctx, keys...).Result()
}

Expand Down
8 changes: 4 additions & 4 deletions gateway/pkg/utils/headers.go
Expand Up @@ -16,11 +16,11 @@ import (

var ErrGatewayConfigHeaderNotValid = errors.New(fmt.Errorf("x-ms-config header is not valid"))

func isJSON(s string, v interface{}) bool {
func isJSON(s string, v any) bool {
return json.Unmarshal([]byte(s), v) == nil
}

func UnmarshalConfigHeaders(header http.Header, v interface{}) error {
func UnmarshalConfigHeaders(header http.Header, v any) error {
msconfig := header.Get(constants.XMSProvider)
if msconfig == "" && isJSON(msconfig, v) {
return ErrGatewayConfigHeaderNotValid
Expand All @@ -29,7 +29,7 @@ func UnmarshalConfigHeaders(header http.Header, v interface{}) error {
}

// UnmarshalHeader unmarshals an http.Header into a struct
func UnmarshalHeader(header http.Header, v interface{}) error {
func UnmarshalHeader(header http.Header, v any) error {
fields := reflect.ValueOf(v).Elem()

for i := 0; i < fields.NumField(); i++ {
Expand Down Expand Up @@ -70,7 +70,7 @@ func setFieldValue(field reflect.Value, value string) {
}

// ValidateHeaders is a generic function to validate any structure with the `validate` struct tag.
func ValidateHeaders(data interface{}) error {
func ValidateHeaders(data any) error {
validate := validator.New()
if err := validate.Struct(data); err != nil {
errorMessages := []string{}
Expand Down

0 comments on commit d27c8fc

Please sign in to comment.