From 5b5c73457b691b372a9c75cd2c44ca7db48c3c36 Mon Sep 17 00:00:00 2001 From: Vasiliy Tolstov Date: Tue, 7 Apr 2020 17:38:27 +0300 Subject: [PATCH] api/router/static: allow to specify body dst (#1486) Signed-off-by: Vasiliy Tolstov --- rpc.go | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/rpc.go b/rpc.go index 83a0d87..f4d23bc 100644 --- a/rpc.go +++ b/rpc.go @@ -300,6 +300,7 @@ func requestPayload(r *http.Request) ([]byte, error) { // allocate maximum matches := make(map[string]interface{}, len(md)) + bodydst := "" // get fields from url path for k, v := range md { @@ -307,6 +308,9 @@ func requestPayload(r *http.Request) ([]byte, error) { if strings.HasPrefix(k, "x-api-field-") { matches[strings.TrimPrefix(k, "x-api-field-")] = v delete(md, k) + } else if k == "x-api-body" { + bodydst = v + delete(md, k) } } @@ -387,8 +391,32 @@ func requestPayload(r *http.Request) ([]byte, error) { } else { return []byte{}, nil } + if bodydst == "" || bodydst == "*" { + if out, err = jsonpatch.MergeMergePatches(out, bodybuf); err == nil { + return out, nil + } + } + dstmap := make(map[string]interface{}) + ps := strings.Split(bodydst, ".") + if len(ps) == 1 { + dstmap[ps[0]] = bodybuf + } else { + em := make(map[string]interface{}) + em[ps[len(ps)-1]] = bodybuf + for i := len(ps) - 2; i > 0; i-- { + nm := make(map[string]interface{}) + nm[ps[i]] = em + em = nm + } + dstmap[ps[0]] = em + } - if out, err = jsonpatch.MergeMergePatches(out, bodybuf); err == nil { + bodyout, err := json.Marshal(dstmap) + if err != nil { + return nil, err + } + + if out, err = jsonpatch.MergeMergePatches(out, bodyout); err == nil { return out, nil }