Skip to content

Commit

Permalink
avoid panic in request error handling (mattermost-community#3528)
Browse files Browse the repository at this point in the history
  • Loading branch information
wiggin77 authored Aug 3, 2022
1 parent e7b5830 commit 1d4a2be
Showing 1 changed file with 12 additions and 4 deletions.
16 changes: 12 additions & 4 deletions server/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -4587,7 +4587,7 @@ func (a *API) errorResponse(w http.ResponseWriter, api string, code int, message
)
}

w.Header().Set("Content-Type", "application/json")
setResponseHeader(w, "Content-Type", "application/json")
data, err := json.Marshal(model.ErrorResponse{Error: message, ErrorCode: code})
if err != nil {
data = []byte("{}")
Expand All @@ -4597,18 +4597,26 @@ func (a *API) errorResponse(w http.ResponseWriter, api string, code int, message
}

func stringResponse(w http.ResponseWriter, message string) {
w.Header().Set("Content-Type", "text/plain")
setResponseHeader(w, "Content-Type", "text/plain")
_, _ = fmt.Fprint(w, message)
}

func jsonStringResponse(w http.ResponseWriter, code int, message string) {
w.Header().Set("Content-Type", "application/json")
setResponseHeader(w, "Content-Type", "application/json")
w.WriteHeader(code)
fmt.Fprint(w, message)
}

func jsonBytesResponse(w http.ResponseWriter, code int, json []byte) {
w.Header().Set("Content-Type", "application/json")
setResponseHeader(w, "Content-Type", "application/json")
w.WriteHeader(code)
_, _ = w.Write(json)
}

func setResponseHeader(w http.ResponseWriter, key string, value string) {
header := w.Header()
if header == nil {
return
}
header.Set(key, value)
}

0 comments on commit 1d4a2be

Please sign in to comment.