Skip to content

Commit

Permalink
add error handler to middlewares
Browse files Browse the repository at this point in the history
  • Loading branch information
hawry committed Jan 12, 2018
1 parent 67a1680 commit 4826209
Show file tree
Hide file tree
Showing 5 changed files with 54 additions and 41 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
*.out
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,7 @@
## Usage

Checkout the GoDoc page for the documentation: https://godoc.org/github.com/Hawry/middlewares

## Testing
To see the test coverage and which lines that are being tested, run:
`go test -coverprofile=cp.out && go tool cover -html=cp.out`
44 changes: 4 additions & 40 deletions error_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package middlewares

import (
"html/template"
"log"
"net/http"
)

Expand All @@ -12,54 +11,20 @@ type errorHandler struct {
body []byte
}

const errBody = `<!doctype HTML>
<html>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{.StatusCode}} - {{.StatusText}}</title>
<style type="text/css">
h1 {
color:#666;
}
.content {
text-align:center;
margin-left: auto;
margin-right: auto;
max-width: 75%;
font-size: 1.5rem;
}
.error-text {
color:#666;
}
</style>
</head>
<body>
<div class="content">
<h1>{{.StatusCode}}</h1>
<p class="error-text">
{{.StatusMessage}}
</p>
</div>
</body>
</html>
`
const errBody = `<!doctype HTML><html><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>{{.StatusCode}} - {{.StatusText}}</title><style type="text/css">h1 {color:#666;}.content {text-align:center;margin-left: auto;margin-right: auto;max-width: 75%;font-size: 1.5rem;}.error-text {color:#666;}</style></head><body><div class="content"><h1>{{.StatusCode}}</h1><p class="error-text">{{.StatusMessage}}</p></div></body></html>`

var errTemplate *template.Template

func init() {
errTemplate = template.Must(template.New("err").Parse(errBody))
}

//ErrorHandler will inject a html response to any error status code
//ErrorHandler will inject a html response to any error status code (400/500 range)
func ErrorHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
eh := &errorHandler{ResponseWriter: w, statusCode: http.StatusOK}
next.ServeHTTP(eh, r)
if eh.statusCode >= 400 && eh.statusCode <= 509 {
// do something
dval := map[string]interface{}{
"StatusCode": eh.statusCode,
"StatusText": http.StatusText(eh.statusCode),
Expand All @@ -70,16 +35,15 @@ func ErrorHandler(next http.Handler) http.Handler {
})
}

// WriteHeader shadows ResponseWriter.Write
// WriteHeader shadows ResponseWriter.Write. If the code is in the 400 or 500 range, the error handler will be used to display the corresponding error page
func (e *errorHandler) WriteHeader(code int) {
e.statusCode = code
e.ResponseWriter.WriteHeader(code)
}

//Write shadows http.ResponseWriter.Write
//Write shadows http.ResponseWriter.Write and writes the body as the text message in the error page
func (e *errorHandler) Write(b []byte) (n int, err error) {
if e.statusCode >= 400 && e.statusCode <= 509 {
log.Printf("err handler write called")
e.body = append(e.body, b...) // use any written text as the error message
} else {
e.ResponseWriter.Write(b)
Expand Down
45 changes: 45 additions & 0 deletions error_handler_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package middlewares

import (
"net/http"
"net/http/httptest"
"testing"

"github.com/stretchr/testify/assert"
)

var tNotFound = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("the page could not be found"))
})

var tFound = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("the page could be found"))
})

func TestErrorBody(t *testing.T) {
req, err := http.NewRequest("GET", "/notfound", nil)
if err != nil {
t.Fatal(err)
}

rr := httptest.NewRecorder()
handler := ErrorHandler(tNotFound)
handler.ServeHTTP(rr, req)
assert.Contains(t, rr.Body.String(), "the page could not be found")
assert.Equal(t, http.StatusNotFound, rr.Code)
}

func TestPassthrough(t *testing.T) {
req, err := http.NewRequest("GET", "/found", nil)
if err != nil {
t.Fatal(err)
}

rr := httptest.NewRecorder()
handler := ErrorHandler(tFound)
handler.ServeHTTP(rr, req)

assert.Contains(t, rr.Body.String(), "the page could be found")
assert.Equal(t, http.StatusOK, rr.Code)
}
1 change: 0 additions & 1 deletion fp_handler.go

This file was deleted.

0 comments on commit 4826209

Please sign in to comment.