Rename package srverrors to httperror

- Package names are preferred to be in singular form¹.
- Since errors are just for HTTP and not generic, I changed the base name to
'http'.
- I didn't name it simply 'error', because it would then conflict with the
- standard 'error' interface.

¹: https://rakyll.org/style-packages/
This commit is contained in:
pancho horrillo
2019-11-20 07:49:38 +01:00
parent 0d66fe9963
commit 206aac5747
9 changed files with 77 additions and 77 deletions
+24
View File
@@ -0,0 +1,24 @@
package httperror
import (
"encoding/json"
"net/http"
)
// A ServerErrMessage represents the reason why the error happened
type ServerErrMessage struct {
Reason string `json:"reason"`
}
// ErrorJSON writes the provided error as a JSON body to the provided
// http.ResponseWriter, after setting the appropriate Content-Type header
func ErrorJSON(w http.ResponseWriter, error string, code int) {
body, _ := json.Marshal(
ServerErrMessage{
Reason: error,
},
)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(code)
_, _ = w.Write(body)
}
+47
View File
@@ -0,0 +1,47 @@
package httperror_test
import (
"encoding/json"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/BBVA/kapow/internal/server/httperror"
)
func TestErrorJSONSetsAppJsonContentType(t *testing.T) {
w := httptest.NewRecorder()
httperror.ErrorJSON(w, "Not Important Here", 0)
if v := w.Result().Header.Get("Content-Type"); v != "application/json; charset=utf-8" {
t.Errorf("Content-Type header mismatch. Expected: %q, got: %q", "application/json; charset=utf-8", v)
}
}
func TestErrorJSONSetsRequestedStatusCode(t *testing.T) {
w := httptest.NewRecorder()
httperror.ErrorJSON(w, "Not Important Here", http.StatusGone)
if v := w.Result().StatusCode; v != http.StatusGone {
t.Errorf("Status code mismatch. Expected: %d, got: %d", http.StatusGone, v)
}
}
func TestErrorJSONSetsBodyCorrectly(t *testing.T) {
expectedReason := "Something Not Found"
w := httptest.NewRecorder()
httperror.ErrorJSON(w, expectedReason, http.StatusNotFound)
errMsg := httperror.ServerErrMessage{}
if bodyBytes, err := ioutil.ReadAll(w.Result().Body); err != nil {
t.Errorf("Unexpected error reading response body: %v", err)
} else if err := json.Unmarshal(bodyBytes, &errMsg); err != nil {
t.Errorf("Response body contains invalid JSON entity: %v", err)
} else if errMsg.Reason != expectedReason {
t.Errorf("Unexpected reason in response. Expected: %q, got: %q", expectedReason, errMsg.Reason)
}
}