From b728bcac15be8c530e91e469a8c11596faeef632 Mon Sep 17 00:00:00 2001 From: batara666 <14269809+codenoid@users.noreply.github.com> Date: Sun, 22 May 2022 21:25:35 +0700 Subject: [PATCH] feat: Engine.AppendKeys Allow c.Keys data to be appended into obj if obj has map[string]any data type --- context.go | 21 +++++++++++++++++++++ gin.go | 3 +++ 2 files changed, 24 insertions(+) diff --git a/context.go b/context.go index 5e53aaf0..c5fb63d7 100644 --- a/context.go +++ b/context.go @@ -823,6 +823,22 @@ func bodyAllowedForStatus(status int) bool { return true } +func appendKeysData(data map[string]any, obj any) any { + copyObj, ok := obj.(map[string]any) + if !ok { + return obj + } + + for key, value := range data { + _, exist := copyObj[key] + if !exist { + copyObj[key] = value + } + } + + return copyObj +} + // Status sets the HTTP response code. func (c *Context) Status(code int) { c.Writer.WriteHeader(code) @@ -905,6 +921,11 @@ func (c *Context) Render(code int, r render.Render) { // It also updates the HTTP code and sets the Content-Type as "text/html". // See http://golang.org/doc/articles/wiki/ func (c *Context) HTML(code int, name string, obj any) { + // Append c.Set() data into object if object is map[string]any + if c.engine.AppendKeys { + obj = appendKeysData(c.Keys, obj) + } + instance := c.engine.HTMLRender.Instance(name, obj) c.Render(code, instance) } diff --git a/gin.go b/gin.go index c2e95f29..1bc62dfa 100644 --- a/gin.go +++ b/gin.go @@ -147,6 +147,9 @@ type Engine struct { // UseH2C enable h2c support. UseH2C bool + // AppendKeys if true, Gin will merge c.Set() data with user obj data + AppendKeys bool + delims render.Delims secureJSONPrefix string HTMLRender render.HTMLRender