Skip to content
This repository has been archived by the owner on Mar 8, 2023. It is now read-only.

Commit

Permalink
DRY error reponses
Browse files Browse the repository at this point in the history
  • Loading branch information
florisvdg committed Mar 19, 2019
1 parent ae270ee commit 0368782
Showing 1 changed file with 24 additions and 41 deletions.
65 changes: 24 additions & 41 deletions pkg/restproxy/rest_proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,27 +66,15 @@ func (p *restProxy) handleSecret(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
err := api.ValidateSecretPath(path)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
io.WriteString(w, err.Error())
writeError(w, err, http.StatusBadRequest)
return
}

switch r.Method {
case "GET":
secret, err := p.client.Secrets().Versions().GetWithData(path)
if err != nil {
var errCode int

if err, ok := err.(errio.PublicStatusError); ok {
errCode = err.StatusCode
}

if errCode == 0 {
errCode = http.StatusInternalServerError
}

w.WriteHeader(errCode)
io.WriteString(w, err.Error())
writeError(w, err, 0)
return
}

Expand All @@ -95,51 +83,29 @@ func (p *restProxy) handleSecret(w http.ResponseWriter, r *http.Request) {
case "POST":
secret, err := ioutil.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
io.WriteString(w, err.Error())
writeError(w, err, http.StatusInternalServerError)
return
}

_, err = p.client.Secrets().Write(path, secret)
if err != nil {
var errCode int

if err, ok := err.(errio.PublicStatusError); ok {
errCode = err.StatusCode
}

statusCode := 0
switch err {
case secrethub.ErrCannotWriteToVersion,
secrethub.ErrEmptySecret,
secrethub.ErrSecretTooBig:
errCode = http.StatusBadRequest
statusCode = http.StatusBadRequest
}

if errCode == 0 {
errCode = http.StatusInternalServerError
}

w.WriteHeader(errCode)
io.WriteString(w, err.Error())
writeError(w, err, statusCode)
return
}

w.WriteHeader(http.StatusCreated)
case "DELETE":
err := p.client.Secrets().Delete(path)
if err != nil {
var errCode int

if err, ok := err.(errio.PublicStatusError); ok {
errCode = err.StatusCode
}

if errCode == 0 {
errCode = http.StatusInternalServerError
}

w.WriteHeader(errCode)
io.WriteString(w, err.Error())
writeError(w, err, 0)
return
}

Expand All @@ -149,3 +115,20 @@ func (p *restProxy) handleSecret(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusMethodNotAllowed)
}
}

// writeError writes an error message and HTTP status code to the ResponseWriter.
// The HTTP status code is derrived from the error, unless overriden by the statusCode argument.
func writeError(w http.ResponseWriter, err error, statusCode int) {
if statusCode == 0 {
if err, ok := err.(errio.PublicStatusError); ok {
statusCode = err.StatusCode
}

if statusCode == 0 {
statusCode = http.StatusInternalServerError
}
}

w.WriteHeader(statusCode)
io.WriteString(w, err.Error())
}

0 comments on commit 0368782

Please sign in to comment.