From d1d5f934860d906eebcdc30751745f39115c3518 Mon Sep 17 00:00:00 2001 From: 1e99 <1e99@1e99.eu> Date: Mon, 16 Dec 2024 22:31:50 +0100 Subject: [PATCH] add static override --- README.md | 3 +++ main.go | 28 +++++++++++++++++++++++++++- routes/serve_files.go | 15 --------------- 3 files changed, 30 insertions(+), 16 deletions(-) delete mode 100644 routes/serve_files.go diff --git a/README.md b/README.md index 3f74fef..b5d9162 100644 --- a/README.md +++ b/README.md @@ -69,6 +69,9 @@ Configuration is done using environment variables. - `ram`: Passwords are stored in RAM. - `dir`: Passwords are stored in a directory. The directory is specified using `PASSED_STORE_DIR_PATH`, which defaults to `passwords`. PassED will create the directory for you. - `PASSED_STORE_CLEAR_INTERVAL`: Time that should pass between clearing expired passwords in seconds, defaults to `30`. +- `PASSED_STATIC_TYPE`: Directory from which static files are served, defaults to `embed`. + - `embed`: Files are served from the files located within the binary. This is recommended. + - `dir`: Files are served from a directory. The directory is specified using `PASSED_STATIC_DIR_PATH`, which defaults to `static`. PassED will not create the directory for you. ## Translators - RoryBD diff --git a/main.go b/main.go index c8aa435..ef0561e 100644 --- a/main.go +++ b/main.go @@ -3,6 +3,7 @@ package main import ( "embed" "errors" + "io/fs" "log" "net/http" "os" @@ -22,6 +23,11 @@ func run() error { return err } + staticFS, err := newStaticFS() + if err != nil { + return err + } + var address string var logRequests bool var maxPasswordLength int @@ -32,7 +38,7 @@ func run() error { mux := http.NewServeMux() handler := http.Handler(mux) - mux.Handle("GET /", routes.ServeFiles(embedFS, "static")) + mux.Handle("GET /", http.FileServerFS(staticFS)) mux.Handle("POST /api/password", routes.CreatePassword(store, maxPasswordLength)) mux.Handle("GET /api/password/{id}", routes.GetPassword(store)) mux.Handle("HEAD /api/password/{id}", routes.HasPassword(store)) @@ -50,6 +56,26 @@ func run() error { return nil } +func newStaticFS() (sfs fs.FS, err error) { + var fsType string + env("PASSED_STATIC_TYPE", &fsType, "embed") + + switch fsType { + case "embed": + sfs, err = fs.Sub(embedFS, "static") + return + case "dir", "directory": + var path string + env("PASSED_STATIC_DIR_PATH", &path, "static") + + sfs = os.DirFS(path) + return + default: + err = errors.New("unkown fs type") + return + } +} + func newStore() (store storage.Store, err error) { var storeType string var clearInterval int diff --git a/routes/serve_files.go b/routes/serve_files.go deleted file mode 100644 index f6de96b..0000000 --- a/routes/serve_files.go +++ /dev/null @@ -1,15 +0,0 @@ -package routes - -import ( - "io/fs" - "net/http" -) - -func ServeFiles(fileSystem fs.FS, pathInFs string) http.Handler { - newFs, err := fs.Sub(fileSystem, pathInFs) - if err != nil { - panic(err) - } - - return http.FileServerFS(newFs) -}