🏗️ Created HTTP delivery for static module

This commit is contained in:
Maxim Lebedev 2024-01-22 08:03:52 +06:00
parent fa2178e597
commit ed87027846
Signed by: toby3d
GPG Key ID: 1F14E25B7C119FC5
3 changed files with 69 additions and 0 deletions

View File

@ -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)
}

View File

@ -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)
}

View File

@ -0,0 +1,2 @@
User-agent: *
Allow: /