Skip to content
Snippets Groups Projects
Commit cfbb4f63 authored by Will McCutchen's avatar Will McCutchen
Browse files

Normalize HTML responses

parent d72e11d0
No related branches found
No related tags found
No related merge requests found
......@@ -26,18 +26,17 @@ func (h *HTTPBin) Index(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Not Found", http.StatusNotFound)
return
}
w.Write(MustAsset("index.html"))
writeHTML(w, MustAsset("index.html"), http.StatusOK)
}
// FormsPost renders an HTML form that submits a request to the /post endpoint
func (h *HTTPBin) FormsPost(w http.ResponseWriter, r *http.Request) {
w.Write(MustAsset("forms-post.html"))
writeHTML(w, MustAsset("forms-post.html"), http.StatusOK)
}
// UTF8 renders an HTML encoding stress test
func (h *HTTPBin) UTF8(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write(MustAsset("utf8.html"))
writeHTML(w, MustAsset("utf8.html"), http.StatusOK)
}
// Get handles HTTP GET requests
......
......@@ -60,7 +60,7 @@ func TestIndex(t *testing.T) {
w := httptest.NewRecorder()
handler.ServeHTTP(w, r)
assertContentType(t, w, "text/html; charset=utf-8")
assertContentType(t, w, htmlContentType)
assertBodyContains(t, w, "go-httpbin")
}
......@@ -76,7 +76,7 @@ func TestFormsPost(t *testing.T) {
w := httptest.NewRecorder()
handler.ServeHTTP(w, r)
assertContentType(t, w, "text/html; charset=utf-8")
assertContentType(t, w, htmlContentType)
assertBodyContains(t, w, `<form method="post" action="/post">`)
}
......@@ -85,7 +85,7 @@ func TestUTF8(t *testing.T) {
w := httptest.NewRecorder()
handler.ServeHTTP(w, r)
assertContentType(t, w, "text/html; charset=utf-8")
assertContentType(t, w, htmlContentType)
assertBodyContains(t, w, `Hello world, Καλημέρα κόσμε, コンニチハ`)
}
......
......@@ -47,13 +47,21 @@ func getURL(r *http.Request) *url.URL {
}
}
func writeJSON(w http.ResponseWriter, body []byte, status int) {
w.Header().Set("Content-Type", jsonContentType)
func writeResponse(w http.ResponseWriter, status int, contentType string, body []byte) {
w.Header().Set("Content-Type", contentType)
w.Header().Set("Content-Length", fmt.Sprintf("%d", len(body)))
w.WriteHeader(status)
w.Write(body)
}
func writeJSON(w http.ResponseWriter, body []byte, status int) {
writeResponse(w, status, jsonContentType, body)
}
func writeHTML(w http.ResponseWriter, body []byte, status int) {
writeResponse(w, status, htmlContentType, body)
}
// parseBody handles parsing a request body into our standard API response,
// taking care to only consume the request body once based on the Content-Type
// of the request. The given Resp will be updated.
......
......@@ -6,6 +6,7 @@ import (
)
const jsonContentType = "application/json; encoding=utf-8"
const htmlContentType = "text/html; charset=utf-8"
type headersResponse struct {
Headers http.Header `json:"headers"`
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment