Skip to content

Commit

Permalink
Add initial version of erkhttp
Browse files Browse the repository at this point in the history
  • Loading branch information
JosiahWitt committed Feb 23, 2020
1 parent 6128fe3 commit 13e2b4f
Show file tree
Hide file tree
Showing 5 changed files with 533 additions and 0 deletions.
21 changes: 21 additions & 0 deletions erkhttp.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Package erkhttp allows embeding HTTP statuses in erk error kinds.
package erkhttp

import "github.com/JosiahWitt/erk"

// HTTPStatusable items can return an HTTP status.
type HTTPStatusable interface {
HTTPStatus() int
}

// GetHTTPStatus from the kind of the provided error.
//
// If the status cannot be found, it defaults to 500 (Internal Server Error), and returns false.
func GetHTTPStatus(err error) (int, bool) {
kind := erk.GetKind(err)
if statusable, ok := kind.(HTTPStatusable); ok {
return statusable.HTTPStatus(), true
}

return 500, false
}
63 changes: 63 additions & 0 deletions erkhttp_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package erkhttp_test

import (
"errors"
"testing"

"github.com/JosiahWitt/erk"
"github.com/JosiahWitt/erkhttp"
"github.com/matryer/is"
)

func TestGetHTTPStatus(t *testing.T) {
table := []struct {
Name string
Err error
ExpectedStatus int
ExpectedOK bool
}{
{
Name: "with erk error with embedded status",
Err: erk.New(ErkItemNotFound{}, "item not found"),
ExpectedStatus: 404,
ExpectedOK: true,
},
{
Name: "with erk error with no embedded status",
Err: erk.New(ErkUnknown{}, "I don't know what happened."),
ExpectedStatus: 500,
ExpectedOK: false,
},
{
Name: "with non-erk error",
Err: errors.New("not an erk error"),
ExpectedStatus: 500,
ExpectedOK: false,
},
{
Name: "with nil error",
Err: nil,
ExpectedStatus: 500,
ExpectedOK: false,
},
}

for _, entry := range table {
entry := entry // Pin range variable

t.Run(entry.Name, func(t *testing.T) {
is := is.New(t)

status, ok := erkhttp.GetHTTPStatus(entry.Err)
is.Equal(status, entry.ExpectedStatus)
is.Equal(ok, entry.ExpectedOK)
})
}
}

type ErkItemNotFound struct {
erk.DefaultKind
erkhttp.StatusNotFound
}

type ErkUnknown struct{ erk.DefaultKind }
8 changes: 8 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module github.com/JosiahWitt/erkhttp

go 1.13

require (
github.com/JosiahWitt/erk v0.5.0
github.com/matryer/is v1.2.0
)
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
github.com/JosiahWitt/erk v0.5.0 h1:2tSb5yAVLRz5SBeApE6KcQchCyxlxQFYBesqg7b7utY=
github.com/JosiahWitt/erk v0.5.0/go.mod h1:OiLS68mTg6Aa3Olx2CHoe3Dg38Uy8MsJzHawpT8aEfQ=
github.com/matryer/is v1.2.0 h1:92UTHpy8CDwaJ08GqLDzhhuixiBUUD1p3AU6PHddz4A=
github.com/matryer/is v1.2.0/go.mod h1:2fLPjFQM9rhQ15aVEtbuwhJinnOqrmgXPNdZsdwlWXA=
Loading

0 comments on commit 13e2b4f

Please sign in to comment.