From 0408d03a29c7aced3d4730df8fee1662cba4a4dd Mon Sep 17 00:00:00 2001 From: Julian Hurst Date: Thu, 23 Jan 2025 03:14:14 +0100 Subject: Initial commit --- .gitignore | 2 ++ go.mod | 3 +++ main.go | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++++ templates/index.html | 32 ++++++++++++++++++++++++++ 4 files changed, 100 insertions(+) create mode 100644 .gitignore create mode 100644 go.mod create mode 100644 main.go create mode 100644 templates/index.html diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..697f5b3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +box +data diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..8a5db1d --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module simpleshare + +go 1.23.5 diff --git a/main.go b/main.go new file mode 100644 index 0000000..6625dfc --- /dev/null +++ b/main.go @@ -0,0 +1,63 @@ +package main + +import ( + "net/http" + "html/template" + "log" + "fmt" + "embed" + "io" + "os" + "path" + "path/filepath" +) + +//go:embed templates +var tmplFS embed.FS + +type BoxHandler struct { + dataPath string +} + +func serve(w http.ResponseWriter, views ...string) { + t, err := template.New("index.html").ParseFS(tmplFS, views...) + if err != nil { + log.Fatal(err) + } + if err := t.Execute(w, nil); err != nil { + log.Fatal(err) + } +} + +func (handler BoxHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + serve(w, "templates/index.html") + return + case http.MethodPost: + filename := filepath.Join(handler.dataPath, path.Base(r.URL.Path)) + log.Printf("boxing %s\n", filename) + f, err := os.Create(filename) + if err != nil { + fmt.Fprint(w, err.Error()) + w.WriteHeader(http.StatusInternalServerError) + return + } + defer r.Body.Close() + io.Copy(f, r.Body) + log.Printf("boxed %s\n", filename) + default: + w.WriteHeader(http.StatusMethodNotAllowed) + } +} + +func main() { + boxHandler := BoxHandler { + "data", + } + err := os.MkdirAll(boxHandler.dataPath, 0750) + if err != nil { + log.Fatal(err) + } + log.Fatal(http.ListenAndServe(":8080", boxHandler)) +} diff --git a/templates/index.html b/templates/index.html new file mode 100644 index 0000000..220c8c9 --- /dev/null +++ b/templates/index.html @@ -0,0 +1,32 @@ + + + + + box + + + +

Box

+
Server for uploading files. Use the form here or send a POST request to /[filename] with the content of the file in the body.
+

+
+ + + -- cgit v1.2.3