From 1584c70f3298679dddd020a40bae663bc730e5e1 Mon Sep 17 00:00:00 2001 From: Jerry <85411418@qq.com> Date: Wed, 23 Oct 2024 19:27:07 +0800 Subject: [PATCH] update --- body_map.go | 20 ++++++++++++++++++++ body_map_test.go | 19 +++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/body_map.go b/body_map.go index 4fd07fa..336bd01 100644 --- a/body_map.go +++ b/body_map.go @@ -62,6 +62,7 @@ func (bm BodyMap) GetString(key string) string { return v } +// Deprecated: Use GetAny instead. // 获取原始参数 func (bm BodyMap) GetInterface(key string) any { if bm == nil { @@ -70,6 +71,25 @@ func (bm BodyMap) GetInterface(key string) any { return bm[key] } +// 获取原始参数 +func (bm BodyMap) GetAny(key string) any { + if bm == nil { + return nil + } + return bm[key] +} + +// 解析到结构体指针 +func (bm BodyMap) Decode(key string, ptr any) error { + if bm == nil { + return errors.New("BodyMap is nil") + } + if err := json.Unmarshal([]byte(bm.GetString(key)), ptr); err != nil { + return err + } + return nil +} + // 删除参数 func (bm BodyMap) Remove(key string) { delete(bm, key) diff --git a/body_map_test.go b/body_map_test.go index 337acb2..ced94b3 100644 --- a/body_map_test.go +++ b/body_map_test.go @@ -145,3 +145,22 @@ func TestBodyUnmarshal(t *testing.T) { } xlog.Debug("bm:", bm) } + +func TestSetSlice(t *testing.T) { + xlog.SetLevel(xlog.DebugLevel) + type User struct { + Name string `json:"name"` + Age int `json:"age"` + } + var us []*User + for i := 0; i < 3; i++ { + us = append(us, &User{ + Name: "Jerry", + Age: i, + }) + } + bm := make(BodyMap) + bm.Set("slice", us) + jb := bm.JsonBody() + xlog.Debug("bm: ", jb) +}