Skip to content

Commit 43b61fe

Browse files
committed
fix: use golang's http.Error to send errors
This: 1. Ensures the correct content type. 2. Tells browsers not to sniff the content type. This prevents any nasties from happening...
1 parent 1995f5c commit 43b61fe

File tree

2 files changed

+7
-9
lines changed

2 files changed

+7
-9
lines changed

http/errors_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ func TestErrors(t *testing.T) {
9292
cmds.EncLong: "foobar",
9393
},
9494
status: "400 Bad Request",
95-
bodyStr: `invalid encoding: foobar`,
95+
bodyStr: "invalid encoding: foobar\n",
9696
},
9797

9898
{

http/handler.go

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -96,8 +96,7 @@ func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
9696
}()
9797

9898
if !allowOrigin(r, h.cfg) || !allowReferer(r, h.cfg) {
99-
w.WriteHeader(http.StatusForbidden)
100-
w.Write([]byte("403 - Forbidden"))
99+
http.Error(w, "403 - Forbidden", http.StatusForbidden)
101100
log.Warningf("API blocked request to %s. (possible CSRF)", r.URL)
102101
return
103102
}
@@ -122,12 +121,12 @@ func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
122121

123122
req, err := parseRequest(r, h.root)
124123
if err != nil {
124+
status := http.StatusBadRequest
125125
if err == ErrNotFound {
126-
w.WriteHeader(http.StatusNotFound)
127-
} else {
128-
w.WriteHeader(http.StatusBadRequest)
126+
status = http.StatusNotFound
129127
}
130-
w.Write([]byte(err.Error()))
128+
129+
http.Error(w, err.Error(), status)
131130
return
132131
}
133132

@@ -146,8 +145,7 @@ func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
146145

147146
re, err := NewResponseEmitter(w, r.Method, req, withRequestBodyEOFChan(bodyEOFChan))
148147
if err != nil {
149-
w.WriteHeader(http.StatusBadRequest)
150-
w.Write([]byte(err.Error()))
148+
http.Error(w, err.Error(), http.StatusBadRequest)
151149
return
152150
}
153151

0 commit comments

Comments
 (0)