From aaac528e89315efc024b5274a22fa73d63f5b8ee Mon Sep 17 00:00:00 2001 From: nikhil Date: Thu, 6 Jul 2023 15:57:25 +0545 Subject: [PATCH] FEAT: add function to map interface --- utils/helpers.go | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/utils/helpers.go b/utils/helpers.go index be7750e..67688a2 100644 --- a/utils/helpers.go +++ b/utils/helpers.go @@ -2,6 +2,7 @@ package utils import ( "golang.org/x/crypto/bcrypt" + "reflect" ) func CompareHashAndPlainPassword(HashedPassword, PlainPassword string) bool { @@ -10,3 +11,27 @@ func CompareHashAndPlainPassword(HashedPassword, PlainPassword string) bool { } return true } + +// ToMap takes in an interface{} and converts it into a map[string]interface{} representation. +func ToMap(data interface{}) map[string]interface{} { + result := make(map[string]interface{}) + reflectValue := reflect.ValueOf(data) + reflectType := reflect.TypeOf(data) + + for i := 0; i < reflectValue.NumField(); i++ { + fieldValue := reflectValue.Field(i) + fieldType := reflectType.Field(i) + + if fieldValue.Kind() == reflect.Struct { + nestedFields := ToMap(fieldValue.Interface()) + for nestedKey, nestedValue := range nestedFields { + result[nestedKey] = nestedValue + } + } + + if fieldValue.Kind() != reflect.Struct { + result[fieldType.Name] = fieldValue.Interface() + } + } + return result +}