summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--go.mod2
-rw-r--r--main.go26
-rw-r--r--templates/index.html6
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 @@
<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)