diff --git a/go.mod b/go.mod index 7184081..6cae926 100644 --- a/go.mod +++ b/go.mod @@ -3,3 +3,5 @@ module git.t-juice.club/torjus/gpaste go 1.17 require github.com/google/uuid v1.3.0 + +require github.com/go-chi/chi/v5 v5.0.7 diff --git a/go.sum b/go.sum index 3dfe1c9..aff816d 100644 --- a/go.sum +++ b/go.sum @@ -1,2 +1,4 @@ +github.com/go-chi/chi/v5 v5.0.7 h1:rDTPXLDHGATaeHvVlLcR4Qe0zftYethFucbjVQ1PxU8= +github.com/go-chi/chi/v5 v5.0.7/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8= github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= diff --git a/http.go b/http.go index cb3bae9..8d5de92 100644 --- a/http.go +++ b/http.go @@ -1 +1,80 @@ package gpaste + +import ( + "encoding/json" + "io" + "net/http" + + "github.com/go-chi/chi/v5" + "github.com/google/uuid" +) + +type HTTPServer struct { + store FileStore + http.Server +} + +func NewHTTPServer(store FileStore) *HTTPServer { + srv := &HTTPServer{ + store: store, + } + + r := chi.NewRouter() + r.Get("/", srv.HandlerIndex) + r.Post("/api/file", srv.HandlerAPIFilePost) + r.Get("/api/file/{id}", srv.HandlerAPIFileGet) + srv.Handler = r + + return srv +} + +func (s *HTTPServer) HandlerIndex(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte("index")) +} + +func (s *HTTPServer) HandlerAPIFilePost(w http.ResponseWriter, r *http.Request) { + f := &File{ + ID: uuid.Must(uuid.NewRandom()).String(), + Body: r.Body, + } + + err := s.store.Store(f) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + return + } + var resp = struct { + Message string `json:"message"` + ID string `json:"id"` + URL string `json:"url"` + }{ + Message: "OK", + ID: f.ID, + URL: "TODO", + } + w.WriteHeader(http.StatusAccepted) + encoder := json.NewEncoder(w) + if err := encoder.Encode(&resp); err != nil { + // TODO: LOG + } +} + +func (s *HTTPServer) HandlerAPIFileGet(w http.ResponseWriter, r *http.Request) { + id := chi.URLParam(r, "id") + if id == "" { + w.WriteHeader(http.StatusBadRequest) + return + } + + f, err := s.store.Get(id) + if err != nil { + // TODO: LOG + w.WriteHeader(http.StatusInternalServerError) + return + } + + w.WriteHeader(http.StatusOK) + if _, err := io.Copy(w, f.Body); err != nil { + // TODO: Log + } +}