diff --git a/internal/static/delivery/http/static_http.go b/internal/static/delivery/http/static_http.go new file mode 100644 index 0000000..01206e0 --- /dev/null +++ b/internal/static/delivery/http/static_http.go @@ -0,0 +1,34 @@ +package http + +import ( + "errors" + "io/fs" + "net/http" + "path" + "strings" + + "source.toby3d.me/toby3d/home/internal/static" +) + +type Handler struct { + static static.UseCase +} + +func NewHandler(static static.UseCase) *Handler { + return &Handler{static: static} +} + +func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + s, err := h.static.Do(r.Context(), strings.TrimPrefix(path.Clean(r.URL.Path), "/")) + if err != nil { + if errors.Is(err, fs.ErrNotExist) { + http.NotFound(w, r) + } else { + http.Error(w, err.Error(), http.StatusInternalServerError) + } + + return + } + + http.ServeContent(w, r, s.Name(), s.ModTime(), s) +} diff --git a/internal/static/delivery/http/static_http_test.go b/internal/static/delivery/http/static_http_test.go new file mode 100644 index 0000000..85443a8 --- /dev/null +++ b/internal/static/delivery/http/static_http_test.go @@ -0,0 +1,33 @@ +package http_test + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "source.toby3d.me/toby3d/home/internal/domain" + delivery "source.toby3d.me/toby3d/home/internal/static/delivery/http" + repository "source.toby3d.me/toby3d/home/internal/static/repository/stub" + "source.toby3d.me/toby3d/home/internal/static/usecase" + "source.toby3d.me/toby3d/home/internal/testutil" +) + +func TestHandler_ServeHTTP(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest(http.MethodGet, "/robots.txt", nil) + w := httptest.NewRecorder() + + testStatic := domain.NewStatic(strings.NewReader("User-agent: *\nAllow: /"), time.Now().UTC(), "robots.txt") + delivery.NewHandler(usecase.NewStaticUseCase(repository.NewStubStaticRepository(nil, testStatic, false))). + ServeHTTP(w, req) + + resp := w.Result() + if expect := http.StatusOK; resp.StatusCode != expect { + t.Errorf("%s %s = %d, want %d", req.Method, req.RequestURI, resp.StatusCode, expect) + } + + testutil.GoldenEqual(t, resp.Body) +} diff --git a/internal/static/delivery/http/testdata/Handler_ServeHTTP.golden b/internal/static/delivery/http/testdata/Handler_ServeHTTP.golden new file mode 100755 index 0000000..14267e9 --- /dev/null +++ b/internal/static/delivery/http/testdata/Handler_ServeHTTP.golden @@ -0,0 +1,2 @@ +User-agent: * +Allow: / \ No newline at end of file