From b23201e4ea65403625b80573907d270b9055dafc Mon Sep 17 00:00:00 2001 From: Julian Hurst Date: Thu, 23 Jan 2025 11:45:36 +0100 Subject: Return resource ID and allow getting resources --- go.mod | 2 ++ main.go | 26 ++++++++++++++++++++++++-- templates/index.html | 6 ++++++ 3 files changed, 32 insertions(+), 2 deletions(-) diff --git a/go.mod b/go.mod index 4b64270..3aba2c6 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,5 @@ module box go 1.23 + +require github.com/google/uuid v1.6.0 // indirect diff --git a/main.go b/main.go index b416971..9df05b9 100644 --- a/main.go +++ b/main.go @@ -11,6 +11,8 @@ import ( "path" "path/filepath" "flag" + + "github.com/google/uuid" ) //go:embed templates @@ -35,7 +37,19 @@ func serve(w http.ResponseWriter, token string, views ...string) { func (handler BoxHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodGet: - serve(w, handler.token, "templates/index.html") + if r.URL.Path == "/" { + serve(w, handler.token, "templates/index.html") + } else { + resourceId := path.Base(r.URL.Path) + f, err := os.Open(filepath.Join(handler.dataPath, resourceId)) + if err != nil { + log.Println(err) + fmt.Fprint(w, err.Error()) + w.WriteHeader(http.StatusBadRequest) + return + } + io.Copy(w, f) + } return case http.MethodPost: token := r.Header.Get("X-Upload-Token") @@ -44,7 +58,14 @@ func (handler BoxHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusUnauthorized) return } - filename := filepath.Join(handler.dataPath, path.Base(r.URL.Path)) + u, err := uuid.NewRandom() + if err != nil { + log.Println(err) + fmt.Fprint(w, err.Error()) + w.WriteHeader(http.StatusInternalServerError) + return + } + filename := filepath.Join(handler.dataPath, u.String()) log.Printf("boxing %s\n", filename) f, err := os.Create(filename) if err != nil { @@ -55,6 +76,7 @@ func (handler BoxHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } defer r.Body.Close() io.Copy(f, r.Body) + w.Header().Add("X-Resource-ID", filepath.Base(filename)) log.Printf("boxed %s\n", filename) default: w.WriteHeader(http.StatusMethodNotAllowed) diff --git a/templates/index.html b/templates/index.html index bafd7eb..c487165 100644 --- a/templates/index.html +++ b/templates/index.html @@ -5,6 +5,7 @@ box