http: respondCommon to do common responses

This commit is contained in:
Mitchell Hashimoto
2015-03-31 21:29:53 -07:00
parent fd1d9b1631
commit 8c707df4bc
3 changed files with 16 additions and 8 deletions

View File

@@ -57,9 +57,18 @@ func respondError(w http.ResponseWriter, status int, err error) {
enc.Encode(resp)
}
func respondErrorResponse(w http.ResponseWriter, resp *logical.Response) {
err := fmt.Errorf("%s", resp.Data["error"].(string))
respondError(w, http.StatusBadRequest, err)
func respondCommon(w http.ResponseWriter, resp *logical.Response) bool {
if resp == nil {
return false
}
if resp.IsError() {
err := fmt.Errorf("%s", resp.Data["error"].(string))
respondError(w, http.StatusBadRequest, err)
return true
}
return false
}
func respondOk(w http.ResponseWriter, body interface{}) {

View File

@@ -59,12 +59,11 @@ func handleLogical(core *vault.Core) http.Handler {
respondError(w, http.StatusInternalServerError, err)
return
}
if op == logical.ReadOperation && resp == nil {
respondError(w, http.StatusNotFound, nil)
if respondCommon(w, resp) {
return
}
if resp.IsError() {
respondErrorResponse(w, resp)
if op == logical.ReadOperation && resp == nil {
respondError(w, http.StatusNotFound, nil)
return
}

View File

@@ -26,7 +26,6 @@ func TestLogical(t *testing.T) {
var actual map[string]interface{}
expected := map[string]interface{}{
"vault_id": "",
"renewable": false,
"lease_duration": float64(0),
"data": map[string]interface{}{
@@ -35,6 +34,7 @@ func TestLogical(t *testing.T) {
}
testResponseStatus(t, resp, 200)
testResponseBody(t, resp, &actual)
delete(actual, "vault_id")
if !reflect.DeepEqual(actual, expected) {
t.Fatalf("bad: %#v", actual)
}