Skip to content

Commit dd0f325

Browse files
authored
fix: Fix error code in page 404 (#42)
1 parent 4592d58 commit dd0f325

2 files changed

Lines changed: 71 additions & 0 deletions

File tree

internal/web/handlers/base.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ func sendErrorMsg(w http.ResponseWriter, r *http.Request, errorMsg string) {
3737
}
3838

3939
func (h *Handlers) Page404(w http.ResponseWriter, r *http.Request) {
40+
w.WriteHeader(http.StatusNotFound)
4041
templ.Handler(
4142
page.Index(view.NotFoundComponent()),
4243
).ServeHTTP(w, r)

internal/web/handlers/base_test.go

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package handlers
2+
3+
import (
4+
"io"
5+
"net/http"
6+
"net/http/httptest"
7+
"testing"
8+
9+
"github.com/stretchr/testify/assert"
10+
)
11+
12+
func Test_sendErrorMsg(t *testing.T) {
13+
testCases := []struct {
14+
name string
15+
errorMsg string
16+
body io.Reader
17+
expectedStatus int
18+
expectedBody string
19+
}{
20+
{
21+
name: "invalid request",
22+
body: nil,
23+
errorMsg: "MSG",
24+
expectedStatus: http.StatusBadRequest,
25+
expectedBody: `<div class="error-msg" role="alert"><strong>Error: </strong> <span>MSG</span></div>`,
26+
},
27+
}
28+
29+
for _, tc := range testCases {
30+
t.Run(tc.name, func(t *testing.T) {
31+
w := httptest.NewRecorder()
32+
r := httptest.NewRequest(http.MethodGet, "/", tc.body)
33+
34+
sendErrorMsg(w, r, tc.errorMsg)
35+
36+
assert.Equal(t, tc.expectedStatus, w.Result().StatusCode,
37+
"unexpected status code. Expected :%d, got: %d", tc.expectedStatus, w.Result().StatusCode)
38+
39+
body, _ := io.ReadAll(w.Result().Body)
40+
assert.Equal(t, tc.expectedBody, string(body), "expected response body")
41+
})
42+
}
43+
}
44+
45+
func Test_Page404(t *testing.T) {
46+
testCases := []struct {
47+
name string
48+
body io.Reader
49+
expectedStatus int
50+
}{
51+
{
52+
name: "not found page",
53+
body: nil,
54+
expectedStatus: http.StatusNotFound,
55+
},
56+
}
57+
58+
for _, tc := range testCases {
59+
t.Run(tc.name, func(t *testing.T) {
60+
w := httptest.NewRecorder()
61+
r := httptest.NewRequest(http.MethodGet, "/", tc.body)
62+
63+
handler := &Handlers{}
64+
handler.Page404(w, r)
65+
66+
assert.Equal(t, tc.expectedStatus, w.Result().StatusCode,
67+
"unexpected status code. Expected :%d, got: %d", tc.expectedStatus, w.Result().StatusCode)
68+
})
69+
}
70+
}

0 commit comments

Comments
 (0)