Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions responder.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ func JSON(w http.ResponseWriter, r *http.Request, v interface{}) {
enc := json.NewEncoder(buf)
enc.SetEscapeHTML(true)
if err := enc.Encode(v); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}

Expand All @@ -112,7 +112,7 @@ func JSON(w http.ResponseWriter, r *http.Request, v interface{}) {
func XML(w http.ResponseWriter, r *http.Request, v interface{}) {
b, err := xml.Marshal(v)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}

Expand Down Expand Up @@ -184,7 +184,7 @@ func channelEventStream(w http.ResponseWriter, r *http.Request, v interface{}) {

bytes, err := json.Marshal(v)
if err != nil {
w.Write([]byte(fmt.Sprintf("event: error\ndata: {\"error\":\"%v\"}\n\n", err))) //nolint:errcheck
w.Write([]byte("event: error\ndata: {\"error\":\"Internal Server Error\"}\n\n")) //nolint:errcheck
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
Expand Down
43 changes: 43 additions & 0 deletions responder_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package render

import (
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
)

type leakyJSON struct{}

func (leakyJSON) MarshalJSON() ([]byte, error) {
return nil, errors.New("secret token xyz")
}

func TestJSONDoesNotLeakEncodeError(t *testing.T) {
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/", nil)
JSON(rec, req, leakyJSON{})
if rec.Code != http.StatusInternalServerError {
t.Fatalf("status = %d, want 500", rec.Code)
}
body := rec.Body.String()
if strings.Contains(body, "secret token") {
t.Fatalf("leaked encode error: %q", body)
}
if !strings.Contains(body, http.StatusText(http.StatusInternalServerError)) {
t.Fatalf("body = %q, want Internal Server Error", body)
}
}

func TestJSONOK(t *testing.T) {
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/", nil)
JSON(rec, req, M{"ok": true})
if rec.Code != http.StatusOK {
t.Fatalf("status = %d", rec.Code)
}
if got := rec.Body.String(); !strings.Contains(got, `"ok":true`) {
t.Fatalf("body = %q", got)
}
}