Skip to content

Commit b08f630

Browse files
committed
Fixed HTTPAnswerJSON behaviour when receiving string data
1 parent a4feb74 commit b08f630

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

handyhttp.go

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,7 @@ func HTTPRequestAsFloat64(r *http.Request, key string, decimalSeparator rune) fl
9191
}
9292

9393
// HTTPJSONBodyToStruct decode json to a given anatomically compatible struct
94+
// THIS ROUTINE IS BEEN DEPRECATED. Use HTTPJSONToStruct() instead.
9495
func HTTPJSONBodyToStruct(r *http.Request, targetStruct interface{}) bool {
9596
decoder := json.NewDecoder(r.Body)
9697

@@ -121,10 +122,16 @@ func HTTPJSONToStruct(r *http.Request, targetStruct interface{}, closeBody bool)
121122

122123
// HTTPAnswerJSON converts the given data as json, set the content-type header and write it to requester
123124
func HTTPAnswerJSON(w http.ResponseWriter, data interface{}) error {
124-
jb, err := json.Marshal(data)
125-
126-
if err != nil {
127-
return err
125+
var jb []byte
126+
127+
if j1, ok := data.(string); ok {
128+
jb = []byte(j1)
129+
} else {
130+
if j2, err := json.Marshal(data); err != nil {
131+
return err
132+
} else {
133+
jb = j2
134+
}
128135
}
129136

130137
w.Header().Set("Content-Type", "application/json; charset=utf-8")

0 commit comments

Comments
 (0)