diff options
| author | Priyansh <[email protected]> | 2025-08-26 14:23:25 +0530 |
|---|---|---|
| committer | Priyansh <[email protected]> | 2025-08-26 14:23:25 +0530 |
| commit | 0c66e0b7dedda5aab5a5848513ccafffdad66d6b (patch) | |
| tree | c38d2028678860780aa705e4ccc1296baecff94f /utils | |
| parent | d73855da602c874be21f49279acb0e912438d470 (diff) | |
| download | eda-0c66e0b7dedda5aab5a5848513ccafffdad66d6b.tar.xz eda-0c66e0b7dedda5aab5a5848513ccafffdad66d6b.zip | |
basic boilerplate setup
Diffstat (limited to 'utils')
| -rw-r--r-- | utils/shortcuts/render.go | 71 |
1 files changed, 71 insertions, 0 deletions
diff --git a/utils/shortcuts/render.go b/utils/shortcuts/render.go new file mode 100644 index 0000000..19635e2 --- /dev/null +++ b/utils/shortcuts/render.go @@ -0,0 +1,71 @@ +package shortcuts + +import ( + "reflect" + "strings" + + "maps" + + "github.com/gofiber/fiber/v2" +) + +func Render(ctx *fiber.Ctx, name string, bind any) error { + finalData := fiber.Map{} + + ctx.Context().VisitUserValues(func(key []byte, value any) { + finalData[string(key)] = value + }) + + if bind != nil { + switch v := bind.(type) { + case fiber.Map: + maps.Copy(finalData, v) + case map[string]any: + maps.Copy(finalData, v) + default: + structData := structToMap(bind) + maps.Copy(finalData, structData) + } + } + + return ctx.Render(name, finalData) +} + +func RenderWithStatus(ctx *fiber.Ctx, name string, bind any, statusCode int) error { + ctx.Status(statusCode) + return Render(ctx, name, bind) +} + +func structToMap(obj any) map[string]any { + result := make(map[string]any) + + v := reflect.ValueOf(obj) + if v.Kind() == reflect.Ptr { + v = v.Elem() + } + + if v.Kind() != reflect.Struct { + return result + } + + t := v.Type() + for i := range v.NumField() { + field := t.Field(i) + if !field.IsExported() { + continue + } + + key := field.Name + if tag := field.Tag.Get("json"); tag != "" && tag != "-" { + if commaIdx := strings.Index(tag, ","); commaIdx > 0 { + key = tag[:commaIdx] + } else if commaIdx == -1 { + key = tag + } + } + + result[key] = v.Field(i).Interface() + } + + return result +} |
