From 9f6aac08a8e9a0685a21fbe4ee292cb514485f22 Mon Sep 17 00:00:00 2001 From: Bobby Date: Sun, 15 Jun 2025 00:05:43 +0530 Subject: setting up the imageboard --- utils/shortcuts/render.go | 66 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 utils/shortcuts/render.go (limited to 'utils') diff --git a/utils/shortcuts/render.go b/utils/shortcuts/render.go new file mode 100644 index 0000000..ba83a81 --- /dev/null +++ b/utils/shortcuts/render.go @@ -0,0 +1,66 @@ +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 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 +} -- cgit v1.2.3