Skip to content

Commit

Permalink
Fixed HTTPAnswerJSON behaviour when receiving string data
Browse files Browse the repository at this point in the history
  • Loading branch information
miguelpragier committed Jun 24, 2020
1 parent a4feb74 commit b08f630
Showing 1 changed file with 11 additions and 4 deletions.
15 changes: 11 additions & 4 deletions handyhttp.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ func HTTPRequestAsFloat64(r *http.Request, key string, decimalSeparator rune) fl
}

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

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

// HTTPAnswerJSON converts the given data as json, set the content-type header and write it to requester
func HTTPAnswerJSON(w http.ResponseWriter, data interface{}) error {
jb, err := json.Marshal(data)

if err != nil {
return err
var jb []byte

if j1, ok := data.(string); ok {
jb = []byte(j1)
} else {
if j2, err := json.Marshal(data); err != nil {
return err
} else {
jb = j2
}
}

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

0 comments on commit b08f630

Please sign in to comment.