diff --git a/middleware/go.mod b/go.mod similarity index 82% rename from middleware/go.mod rename to go.mod index f090bbd..175794b 100644 --- a/middleware/go.mod +++ b/go.mod @@ -1,11 +1,14 @@ -module gitlab.com/durfy/durpify/middleware +module gitlab.com/durfy/durpify -go 1.24.4 +go 1.25 require ( github.com/MicahParks/keyfunc v1.9.0 + github.com/a-h/templ v0.3.960 github.com/charmbracelet/log v0.4.2 github.com/golang-jwt/jwt/v4 v4.5.2 + gitlab.com/durfy/durpify/handlers v0.0.0-20250708105701-c59d09e4c9da + gopkg.in/yaml.v3 v3.0.1 ) require ( @@ -23,5 +26,5 @@ require ( github.com/rivo/uniseg v0.4.7 // indirect github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect golang.org/x/exp v0.0.0-20231006140011-7918f672742d // indirect - golang.org/x/sys v0.30.0 // indirect + golang.org/x/sys v0.34.0 // indirect ) diff --git a/middleware/go.sum b/go.sum similarity index 81% rename from middleware/go.sum rename to go.sum index 58032cd..a1211a4 100644 --- a/middleware/go.sum +++ b/go.sum @@ -1,5 +1,7 @@ github.com/MicahParks/keyfunc v1.9.0 h1:lhKd5xrFHLNOWrDc4Tyb/Q1AJ4LCzQ48GVJyVIID3+o= github.com/MicahParks/keyfunc v1.9.0/go.mod h1:IdnCilugA0O/99dW+/MkvlyrsX8+L8+x95xuVNtM5jw= +github.com/a-h/templ v0.3.960 h1:trshEpGa8clF5cdI39iY4ZrZG8Z/QixyzEyUnA7feTM= +github.com/a-h/templ v0.3.960/go.mod h1:oCZcnKRf5jjsGpf2yELzQfodLphd2mwecwG4Crk5HBo= github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs= @@ -21,6 +23,8 @@ github.com/go-logfmt/logfmt v0.6.0/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KE github.com/golang-jwt/jwt/v4 v4.4.2/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= github.com/golang-jwt/jwt/v4 v4.5.2 h1:YtQM7lnr8iZ+j5q71MGKkNw9Mn7AjHM68uc9g5fXeUI= github.com/golang-jwt/jwt/v4 v4.5.2/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= @@ -38,10 +42,14 @@ github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOf github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no= github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM= +gitlab.com/durfy/durpify/handlers v0.0.0-20250708105701-c59d09e4c9da h1:iOtV2x/VSKDOlGPkNiOErIs4U3LjFDw9BBzyMnE9cZI= +gitlab.com/durfy/durpify/handlers v0.0.0-20250708105701-c59d09e4c9da/go.mod h1:l/gPuZkaNBq2bKYCUs9uMHOqsxpmDqpn6bMFplZxz1w= golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI= golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc= -golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA= +golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/go.work b/go.work deleted file mode 100644 index 44a5424..0000000 --- a/go.work +++ /dev/null @@ -1,4 +0,0 @@ -go 1.24.4 - -use ./handlers - diff --git a/handlers/go.mod b/handlers/go.mod deleted file mode 100644 index 479ff78..0000000 --- a/handlers/go.mod +++ /dev/null @@ -1,27 +0,0 @@ -module gitlab.com/durfy/durpify/handlers - -go 1.24.4 - -require ( - github.com/a-h/templ v0.3.906 - github.com/charmbracelet/log v0.4.2 - gopkg.in/yaml.v3 v3.0.1 -) - -require ( - github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect - github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect - github.com/charmbracelet/lipgloss v1.1.0 // indirect - github.com/charmbracelet/x/ansi v0.8.0 // indirect - github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd // indirect - github.com/charmbracelet/x/term v0.2.1 // indirect - github.com/go-logfmt/logfmt v0.6.0 // indirect - github.com/lucasb-eyer/go-colorful v1.2.0 // indirect - github.com/mattn/go-isatty v0.0.20 // indirect - github.com/mattn/go-runewidth v0.0.16 // indirect - github.com/muesli/termenv v0.16.0 // indirect - github.com/rivo/uniseg v0.4.7 // indirect - github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect - golang.org/x/exp v0.0.0-20231006140011-7918f672742d // indirect - golang.org/x/sys v0.32.0 // indirect -) diff --git a/handlers/go.sum b/handlers/go.sum deleted file mode 100644 index bca61b0..0000000 --- a/handlers/go.sum +++ /dev/null @@ -1,48 +0,0 @@ -github.com/a-h/templ v0.3.906 h1:ZUThc8Q9n04UATaCwaG60pB1AqbulLmYEAMnWV63svg= -github.com/a-h/templ v0.3.906/go.mod h1:FFAu4dI//ESmEN7PQkJ7E7QfnSEMdcnu7QrAY8Dn334= -github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= -github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= -github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs= -github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk= -github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY= -github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30= -github.com/charmbracelet/log v0.4.2 h1:hYt8Qj6a8yLnvR+h7MwsJv/XvmBJXiueUcI3cIxsyig= -github.com/charmbracelet/log v0.4.2/go.mod h1:qifHGX/tc7eluv2R6pWIpyHDDrrb/AG71Pf2ysQu5nw= -github.com/charmbracelet/x/ansi v0.8.0 h1:9GTq3xq9caJW8ZrBTe0LIe2fvfLR/bYXKTx2llXn7xE= -github.com/charmbracelet/x/ansi v0.8.0/go.mod h1:wdYl/ONOLHLIVmQaxbIYEC/cRKOQyjTkowiI4blgS9Q= -github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd h1:vy0GVL4jeHEwG5YOXDmi86oYw2yuYUGqz6a8sLwg0X8= -github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs= -github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ= -github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/go-logfmt/logfmt v0.6.0 h1:wGYYu3uicYdqXVgoYbvnkrPVXkuLM1p1ifugDMEdRi4= -github.com/go-logfmt/logfmt v0.6.0/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs= -github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= -github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= -github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= -github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= -github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= -github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc= -github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= -github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc= -github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= -github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= -github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= -github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= -github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= -github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no= -github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM= -golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI= -golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo= -golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20= -golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= -gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/handlers/handlers_test.go b/handlers/handlers_test.go deleted file mode 100644 index bc636a3..0000000 --- a/handlers/handlers_test.go +++ /dev/null @@ -1,145 +0,0 @@ -package handlers - -import ( - "encoding/json" - "net/http" - "net/http/httptest" - "reflect" - "testing" -) - -func TestSendResponseStandardMessage(t *testing.T) { - message := &BasicMessage{ - Message: "Hello World!", - } - resp := &StandardMessage{ - Status: http.StatusAccepted, - Message: message, - } - w := httptest.NewRecorder() - resp.SendReponse(w) - - // Check the status code is set correctly - if w.Code != 202 { - t.Errorf("Expected status code to be 202, but got %d", w.Code) - } - - // Check that the content type header is set to "application/json" - contentType := w.Header().Get("Content-Type") - if contentType != "application/json" { - t.Errorf( - "Expected content type to be 'application/json', but got %s", - contentType, - ) - } - - // Check that the message is written to the response body correctly - response := &BasicMessage{} - err := json.NewDecoder(w.Body).Decode(response) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(message, response) { - t.Errorf("Expected body to be %s but got %s", message, response) - } -} - -func TestSendResponseStandardError(t *testing.T) { - resp := &StandardError{ - Status: http.StatusInternalServerError, - Message: "An error has occured", - Description: []string{"An Error"}, - } - - w := httptest.NewRecorder() - resp.SendReponse(w) - - // Check the status code is set correctly - if w.Code != 500 { - t.Errorf("Expected status code to be 500, but got %d", w.Code) - } - - // Check that the content type header is set to "application/json" - contentType := w.Header().Get("Content-Type") - if contentType != "application/json" { - t.Errorf( - "Expected content type to be 'application/json',"+ - " but got %s", - contentType, - ) - } - - // Check that the message is written to the response body correctly - response := &StandardError{} - err := json.NewDecoder(w.Body).Decode(response) - if err != nil { - t.Fatal(err) - } - - if response.Message != resp.Message { - t.Errorf( - "Expected Message of %s but got %s", - resp.Message, - response.Message, - ) - } - - if !reflect.DeepEqual(resp, response) { - t.Errorf("Expected Message of %v but got %v", resp, response) - } -} - -// NewFailureResponse returns a new instance of StandardError with the given -// message, status code and description. -func TestNewFailureResponse(t *testing.T) { - message := "An error has occured" - status := http.StatusInternalServerError - description := []string{"An Error"} - resp := NewFailureResponse(message, status, description) - - if resp.Status != status { - t.Errorf( - "Expected Status to be %d but got %d", - status, - resp.Status, - ) - } - if resp.Message != message { - t.Errorf( - "Expected Status to be %s but got %s", - message, - resp.Message, - ) - } - if !reflect.DeepEqual(description, resp.Description) { - t.Errorf( - "Expected Status to be %v but got %v", - description, - resp.Description, - ) - } -} - -func TestNewMessageResponse(t *testing.T) { - - message := &BasicMessage{ - Message: "Hello World!", - } - - resp := NewMessageResponse(message, http.StatusOK) - - if resp.Status != http.StatusOK { - t.Errorf( - "Expected Status to be %d but got %d", - http.StatusOK, - resp.Status, - ) - } - if !reflect.DeepEqual(message, resp.Message) { - t.Errorf( - "Expected Message to be %s but got %s", - message, - resp.Message, - ) - } -} diff --git a/middleware/auth.go b/middleware/auth.go index c3e50f0..10a6735 100644 --- a/middleware/auth.go +++ b/middleware/auth.go @@ -31,85 +31,90 @@ type StandardMessage struct { } func (cfg *AuthConfig) AuthMiddleware(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - var groups []string + return http.HandlerFunc( + func(w http.ResponseWriter, r *http.Request) { + var groups []string - tokenString, err := getToken(w) - if err != nil { - resp := handlers.NewFailureResponse( - err.Error(), - http.StatusUnauthorized, - []string{}, - ) - resp.SendReponse(w) - } - - token, err := cfg.validateToken(tokenString) - if err != nil { - resp := handlers.NewFailureResponse( - "Failed to Validate Token", - http.StatusUnauthorized, - []string{err.Error()}, - ) - resp.SendReponse(w) - } - - claims, ok := token.Claims.(jwt.MapClaims) - if !ok { - resp := handlers.NewFailureResponse( - "Invalid Authorization token claim", - http.StatusUnauthorized, - []string{}, - ) - resp.SendReponse(w) - return - } - - groupsClaim, ok := claims["groups"].([]interface{}) - if !ok { - resp := handlers.NewFailureResponse( - "Missing or invalid groups in the token", - http.StatusUnauthorized, - []string{}, - ) - resp.SendReponse(w) - return - } - - for _, group := range groupsClaim { - if groupName, ok := group.(string); ok { - groups = append(groups, groupName) + tokenString, err := getToken(w) + if err != nil { + resp := handlers.NewFailureResponse( + err.Error(), + http.StatusUnauthorized, + []string{}, + ) + resp.SendReponse(w, r) } - } - isAllowed := false - for _, allowedGroup := range cfg.allowedGroups { - for _, group := range groups { - if group == allowedGroup { - isAllowed = true + token, err := cfg.validateToken(tokenString) + if err != nil { + resp := handlers.NewFailureResponse( + "Failed to Validate Token", + http.StatusUnauthorized, + []string{err.Error()}, + ) + resp.SendReponse(w, r) + } + + claims, ok := token.Claims.(jwt.MapClaims) + if !ok { + resp := handlers.NewFailureResponse( + "Invalid Authorization token claim", + http.StatusUnauthorized, + []string{}, + ) + resp.SendReponse(w, r) + return + } + + groupsClaim, ok := claims["groups"].([]interface{}) + if !ok { + resp := handlers.NewFailureResponse( + "Missing or invalid groups in the token", + http.StatusUnauthorized, + []string{}, + ) + resp.SendReponse(w, r) + return + } + + for _, group := range groupsClaim { + if groupName, ok := group.(string); ok { + groups = append(groups, groupName) + } + } + + isAllowed := false + for _, allowedGroup := range cfg.allowedGroups { + for _, group := range groups { + if group == allowedGroup { + isAllowed = true + break + } + } + if isAllowed { break } } - if isAllowed { - break + + if !isAllowed { + resp := handlers.NewFailureResponse( + "Unauthorized to use this endpoint", + http.StatusUnauthorized, + []string{}, + ) + resp.SendReponse(w, r) + return } - } - if !isAllowed { - resp := handlers.NewFailureResponse( - "Unauthorized to use this endpoint", - http.StatusUnauthorized, - []string{}, - ) - resp.SendReponse(w) - return - } - - next.ServeHTTP(w, r) - }) + next.ServeHTTP(w, r) + }, + ) } -func (cfg *AuthConfig) validateToken(tokenString string) (*jwt.Token, error) { +func (cfg *AuthConfig) validateToken(tokenString string) ( + *jwt.Token, + error, +) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() diff --git a/middleware/recover.go b/middleware/recover.go new file mode 100644 index 0000000..1bf78b8 --- /dev/null +++ b/middleware/recover.go @@ -0,0 +1,29 @@ +package middleware + +import ( + "log" + "net/http" + "runtime/debug" + + "gitlab.com/durfy/durpify/handlers" +) + +func Recovery(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + defer func() { + if err := recover(); err != nil { + msg := "Caught panic: %v, Stack trace: %s" + log.Printf(msg, err, string(debug.Stack())) + + resp := handlers.NewFailureResponse( + "Unternal Server Error", + http.StatusInternalServerError, + []string{err.(string)}, + ) + resp.SendReponse(w, r) + return + } + }() + next.ServeHTTP(w, r) + }) +} diff --git a/handlers/handlers.go b/respond/handlers.go similarity index 94% rename from handlers/handlers.go rename to respond/handlers.go index b076995..83cca95 100644 --- a/handlers/handlers.go +++ b/respond/handlers.go @@ -1,4 +1,4 @@ -package handlers +package respond import ( "encoding/json" @@ -35,7 +35,10 @@ type Response interface { Test(http.Handler) } -func (message *StandardMessage) SendReponse(w http.ResponseWriter, r *http.Request) { +func (message *StandardMessage) SendReponse( + w http.ResponseWriter, + r *http.Request, +) { setHeader(&w, message.Status) contentType := r.Header.Get("Content-Type") @@ -57,7 +60,10 @@ func (message *StandardMessage) SendReponse(w http.ResponseWriter, r *http.Reque } } -func (message *StandardError) SendReponse(w http.ResponseWriter, r *http.Request) { +func (message *StandardError) SendReponse( + w http.ResponseWriter, + r *http.Request, +) { setHeader(&w, message.Status) contentType := r.Header.Get("Content-Type") diff --git a/respond/handlers_test.go b/respond/handlers_test.go new file mode 100644 index 0000000..7502f86 --- /dev/null +++ b/respond/handlers_test.go @@ -0,0 +1,146 @@ +package respond + +// import ( +// "encoding/json" +// "net/http" +// "net/http/httptest" +// "reflect" +// "testing" +// ) +// +// func TestSendResponseStandardMessage(t *testing.T) { +// message := &BasicMessage{ +// Message: "Hello World!", +// } +// resp := &StandardMessage{ +// Status: http.StatusAccepted, +// Message: message, +// } +// w := httptest.NewRecorder() +// resp.SendReponse(w) +// +// // Check the status code is set correctly +// if w.Code != 202 { +// t.Errorf("Expected status code to be 202, but got %d", w.Code) +// } +// +// // Check that the content type header is set to "application/json" +// contentType := w.Header().Get("Content-Type") +// if contentType != "application/json" { +// t.Errorf( +// "Expected content type to be 'application/json', but got %s", +// contentType, +// ) +// } +// +// // Check that the message is written to the response body correctly +// response := &BasicMessage{} +// err := json.NewDecoder(w.Body).Decode(response) +// if err != nil { +// t.Fatal(err) +// } +// if !reflect.DeepEqual(message, response) { +// t.Errorf("Expected body to be %s but got %s", message, response) +// } +// } +// +// func TestSendResponseStandardError(t *testing.T) { +// resp := &StandardError{ +// Status: http.StatusInternalServerError, +// Message: "An error has occured", +// Description: []string{"An Error"}, +// } +// +// w := httptest.NewRecorder() +// resp.SendReponse(w) +// +// // Check the status code is set correctly +// if w.Code != 500 { +// t.Errorf("Expected status code to be 500, but got %d", w.Code) +// } +// +// // Check that the content type header is set to "application/json" +// contentType := w.Header().Get("Content-Type") +// if contentType != "application/json" { +// t.Errorf( +// "Expected content type to be 'application/json',"+ +// " but got %s", +// contentType, +// ) +// } +// +// // Check that the message is written to the response body correctly +// response := &StandardError{} +// err := json.NewDecoder(w.Body).Decode(response) +// if err != nil { +// t.Fatal(err) +// } +// +// if response.Message != resp.Message { +// t.Errorf( +// "Expected Message of %s but got %s", +// resp.Message, +// response.Message, +// ) +// } +// +// if !reflect.DeepEqual(resp, response) { +// t.Errorf("Expected Message of %v but got %v", resp, response) +// } +// } +// +// // NewFailureResponse returns a new instance of StandardError with the given +// // message, status code and description. +// func TestNewFailureResponse(t *testing.T) { +// message := "An error has occured" +// status := http.StatusInternalServerError +// description := []string{"An Error"} +// resp := NewFailureResponse(message, status, description) +// +// if resp.Status != status { +// t.Errorf( +// "Expected Status to be %d but got %d", +// status, +// resp.Status, +// ) +// } +// if resp.Message != message { +// t.Errorf( +// "Expected Status to be %s but got %s", +// message, +// resp.Message, +// ) +// } +// if !reflect.DeepEqual(description, resp.Description) { +// t.Errorf( +// "Expected Status to be %v but got %v", +// description, +// resp.Description, +// ) +// } +// } +// +// func TestNewMessageResponse(t *testing.T) { +// +// message := &BasicMessage{ +// Message: "Hello World!", +// } +// +// resp := NewMessageResponse(message, http.StatusOK) +// +// if resp.Status != http.StatusOK { +// t.Errorf( +// "Expected Status to be %d but got %d", +// http.StatusOK, +// resp.Status, +// ) +// } +// if !reflect.DeepEqual(message, resp.Message) { +// t.Errorf( +// "Expected Message to be %s but got %s", +// message, +// resp.Message, +// ) +// } +// } +//