diff options
| author | Julian Hurst <julian.hurst@digdash.com> | 2025-01-23 11:45:36 +0100 |
|---|---|---|
| committer | Julian Hurst <julian.hurst@digdash.com> | 2025-01-23 11:45:36 +0100 |
| commit | b23201e4ea65403625b80573907d270b9055dafc (patch) | |
| tree | db7a65b2321304de48824634337e09bca2754cdd | |
| parent | 55c77601fdbf39e9aa98185f6dfeaddfecc35fbf (diff) | |
| download | box-b23201e4ea65403625b80573907d270b9055dafc.tar.gz | |
Return resource ID and allow getting resources
| -rw-r--r-- | go.mod | 2 | ||||
| -rw-r--r-- | main.go | 26 | ||||
| -rw-r--r-- | templates/index.html | 6 |
3 files changed, 32 insertions, 2 deletions
@@ -1,3 +1,5 @@ module box go 1.23 + +require github.com/google/uuid v1.6.0 // indirect @@ -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 @@ <title>box</title> <script> function upload() { + let resourceId = ""; token = document.getElementById("token"); if (token == null) { token = ""; @@ -27,8 +28,13 @@ } else { document.getElementById("progress").innerHTML = "Error: unknown"; } + } else { + document.getElementById("progress").innerHTML = "Done: " + resourceId; } } + if (xhr.readyState === xhr.HEADERS_RECEIVED) { + resourceId = xhr.getResponseHeader("X-Resource-ID"); + } } xhr.open("POST", "/" + f.name, true); xhr.setRequestHeader("X-Upload-Token", token) |
