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

Commit

Permalink
More accurate HTTP response codes
Browse files Browse the repository at this point in the history
  • Loading branch information
florisvdg committed Feb 25, 2019
1 parent 1f15f4d commit 6e5148d
Showing 1 changed file with 38 additions and 8 deletions.
46 changes: 38 additions & 8 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (

"github.com/gorilla/mux"
"github.com/keylockerbv/secrethub-go/pkg/api"
"github.com/keylockerbv/secrethub-go/pkg/errio"
"github.com/keylockerbv/secrethub-go/pkg/secrethub"
)

Expand Down Expand Up @@ -54,7 +55,7 @@ func handleSecret(res http.ResponseWriter, req *http.Request) {
path := req.URL.Path
err := api.ValidateSecretPath(path)
if err != nil {
res.WriteHeader(http.StatusNotFound)
res.WriteHeader(http.StatusBadRequest)
io.WriteString(res, err.Error())
return
}
Expand All @@ -63,11 +64,22 @@ func handleSecret(res http.ResponseWriter, req *http.Request) {
case "GET":
sec, err := client.Secrets().Versions().GetWithData(path)
if err != nil {
if err == api.ErrSecretNotFound {
res.WriteHeader(http.StatusOK)
return
var errCode int

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

switch err {
case api.ErrSecretNotFound:
errCode = http.StatusNoContent
}

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

res.WriteHeader(errCode)
io.WriteString(res, err.Error())
return
}
Expand All @@ -85,13 +97,31 @@ func handleSecret(res http.ResponseWriter, req *http.Request) {

_, err = client.Secrets().Write(path, secret)
if err != nil {
res.WriteHeader(http.StatusInternalServerError)
var errCode int

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

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

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

res.WriteHeader(errCode)
io.WriteString(res, err.Error())
return
}

res.WriteHeader(http.StatusOK)
res.WriteHeader(http.StatusCreated)
default:
res.WriteHeader(http.StatusNotFound)
res.Header().Add("Allow", "GET, POST")
res.WriteHeader(http.StatusMethodNotAllowed)
}
}

0 comments on commit 6e5148d

Please sign in to comment.