Skip to content
This repository was archived by the owner on Jan 12, 2020. It is now read-only.

Commit 44dd30e

Browse files
committed
Merged post body into query on POST to GET method override
1 parent d561250 commit 44dd30e

File tree

1 file changed

+48
-1
lines changed

1 file changed

+48
-1
lines changed

method-override.go

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,12 @@
66
package methodoverride
77

88
import (
9+
"encoding/json"
10+
"net/url"
11+
"reflect"
912
"strings"
1013

11-
"github.com/go-rs/rest-api-framework"
14+
rest "github.com/go-rs/rest-api-framework"
1215
)
1316

1417
var (
@@ -28,6 +31,40 @@ func isValidMethod(method string) bool {
2831
return false
2932
}
3033

34+
/**
35+
* Convert json to string
36+
*/
37+
func jsonToString(val interface{}) string {
38+
b, _ := json.Marshal(val)
39+
return string(b)
40+
}
41+
42+
/**
43+
* High-level merge of request json into query
44+
*/
45+
func mergeQuery(query url.Values, body map[string]interface{}) url.Values {
46+
for key, val := range body {
47+
str, ok := val.(string)
48+
if ok {
49+
query.Add(key, str)
50+
} else {
51+
if reflect.TypeOf(val).String() == "[]interface {}" {
52+
for _, val := range val.([]interface{}) {
53+
str, ok = val.(string)
54+
if ok {
55+
query.Add(key, str)
56+
} else {
57+
query.Add(key, jsonToString(val))
58+
}
59+
}
60+
} else {
61+
query.Add(key, jsonToString(val))
62+
}
63+
}
64+
}
65+
return query
66+
}
67+
3168
/**
3269
* Method Override
3370
*/
@@ -36,6 +73,16 @@ func Load() rest.Handler {
3673
method := strings.ToUpper(ctx.Request.Header.Get(header))
3774
if method != "" && isValidMethod(method) {
3875
ctx.Set("OriginalMethod", ctx.Request.Method)
76+
if ctx.Request.Method == "POST" && method == "GET" {
77+
78+
contentType := strings.ToLower(ctx.Request.Header.Get("content-type"))
79+
80+
if contentType == "application/json" {
81+
ctx.Query = mergeQuery(ctx.Query, ctx.Body)
82+
} else if len(ctx.Request.Form) > 0 {
83+
ctx.Query = ctx.Request.Form
84+
}
85+
}
3986
ctx.Request.Method = method
4087
}
4188
}

0 commit comments

Comments
 (0)