initial commit
This commit is contained in:
commit
521f2479e2
14 changed files with 1263 additions and 0 deletions
29
.env.example
Normal file
29
.env.example
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
# Address the HTTP server binds to.
|
||||
LISTEN_ADDR=:8080
|
||||
|
||||
# Directory on disk that is listed and served.
|
||||
ROOT_DIR=./data
|
||||
|
||||
# Title shown in the page header and browser tab.
|
||||
PAGE_TITLE=File List
|
||||
|
||||
# If set, only requests with this Host header are served the directory
|
||||
# listing app; all other hosts get a 404. Leave empty to serve on any host.
|
||||
FILES_VHOST=
|
||||
|
||||
# How often (in seconds) the in-memory file index is fully rebuilt from
|
||||
# disk. The index is also refreshed on-demand shortly after filesystem
|
||||
# changes are detected (best-effort, via fsnotify).
|
||||
CACHE_REFRESH_INTERVAL_SECONDS=30
|
||||
|
||||
# Maximum number of results returned by a single search request.
|
||||
MAX_SEARCH_RESULTS=500
|
||||
|
||||
# gin mode: release, debug, or test.
|
||||
GIN_MODE=release
|
||||
|
||||
# Optional: folder to also write application logs to (in addition to stdout).
|
||||
LOG_FOLDER=
|
||||
|
||||
# Optional: DEBUG, INFO, WARN, ERROR (default INFO).
|
||||
LOG_LEVEL=INFO
|
||||
28
Dockerfile
Normal file
28
Dockerfile
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
FROM golang:1.26-alpine AS builder
|
||||
|
||||
WORKDIR /src
|
||||
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
|
||||
COPY . .
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/pretty-directorylist .
|
||||
|
||||
FROM alpine:3.20
|
||||
|
||||
RUN apk add --no-cache ca-certificates tzdata && \
|
||||
addgroup -S app && adduser -S app -G app
|
||||
|
||||
COPY --from=builder /out/pretty-directorylist /usr/local/bin/pretty-directorylist
|
||||
|
||||
ENV LISTEN_ADDR=:8080 \
|
||||
ROOT_DIR=/data \
|
||||
PAGE_TITLE="File List" \
|
||||
GIN_MODE=release
|
||||
|
||||
VOLUME ["/data"]
|
||||
EXPOSE 8080
|
||||
|
||||
USER app
|
||||
|
||||
ENTRYPOINT ["/usr/local/bin/pretty-directorylist"]
|
||||
93
README.md
Normal file
93
README.md
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
# pretty-directorylist
|
||||
|
||||
A fast, self-hosted directory listing server. It serves a folder from disk
|
||||
as a single-page app with search across all subdirectories, sortable
|
||||
columns, and direct file downloads — backed by a Gin API and a cached,
|
||||
in-memory file index so it stays fast with thousands of files.
|
||||
|
||||
## Features
|
||||
|
||||
- Gin-based HTTP server, frontend and API served from a single Go binary.
|
||||
- Frontend is a single-page app: folder navigation and search happen
|
||||
client-side against a JSON API, with real, bookmarkable URLs (browser
|
||||
back/forward works).
|
||||
- Files are streamed straight from disk via `http.ServeContent` (supports
|
||||
HTTP Range requests) — never buffered fully into memory, so large files
|
||||
don't spike RAM usage.
|
||||
- The file listing is cached in memory and rebuilt on a configurable
|
||||
interval, plus opportunistically when filesystem changes are detected.
|
||||
Directory listings and recursive search are served from that cache, not
|
||||
from disk, so they stay fast even with a few thousand files.
|
||||
- Frontend (HTML/CSS/JS) is embedded into the binary at build time via
|
||||
`go:embed` — the Docker image only needs the compiled binary.
|
||||
- Optional virtual-host restriction so the listing only answers on a
|
||||
specific hostname.
|
||||
|
||||
## Configuration
|
||||
|
||||
All configuration is via environment variables (a `.env` file is loaded
|
||||
automatically if present). See [.env.example](.env.example).
|
||||
|
||||
| Variable | Default | Description |
|
||||
| ---------------------------------- | -------------- | ---------------------------------------------------------------------------------------------- |
|
||||
| `LISTEN_ADDR` | `:8080` | Address the HTTP server binds to. |
|
||||
| `ROOT_DIR` | `./data` | Directory on disk that is listed and served. |
|
||||
| `PAGE_TITLE` | `File List` | Title shown in the page header and browser tab. |
|
||||
| `FILES_VHOST` | *(empty)* | If set, only requests whose `Host` header matches this value are served; others get a 404. |
|
||||
| `CACHE_REFRESH_INTERVAL_SECONDS` | `30` | How often the in-memory file index is fully rebuilt from disk. |
|
||||
| `MAX_SEARCH_RESULTS` | `500` | Maximum number of results returned by a single search request. |
|
||||
| `GIN_MODE` | `release` | Gin mode: `release`, `debug`, or `test`. |
|
||||
| `LOG_FOLDER` | *(empty)* | If set, logs are also written to `<LOG_FOLDER>/application.log` (rotated). |
|
||||
| `LOG_LEVEL` | `INFO` | `DEBUG`, `INFO`, `WARN`, or `ERROR`. |
|
||||
|
||||
## Running locally
|
||||
|
||||
```sh
|
||||
go run .
|
||||
```
|
||||
|
||||
By default this serves `./data` on `http://localhost:8080`.
|
||||
|
||||
## Running with Docker
|
||||
|
||||
```sh
|
||||
docker build -t pretty-directorylist .
|
||||
docker run -p 8080:8080 -v /path/to/files:/data pretty-directorylist
|
||||
```
|
||||
|
||||
Or with environment overrides:
|
||||
|
||||
```sh
|
||||
docker run -p 8080:8080 \
|
||||
-v /path/to/files:/data \
|
||||
-e PAGE_TITLE="My Files" \
|
||||
-e FILES_VHOST=files.example.com \
|
||||
pretty-directorylist
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
The frontend talks to the backend exclusively through this JSON API:
|
||||
|
||||
- `GET /api/dir?path=<relative/path>` — list the direct children of a
|
||||
directory (path relative to `ROOT_DIR`, empty for the root).
|
||||
- `GET /api/search?q=<term>&limit=<n>` — search file/folder names
|
||||
recursively across the whole tree (served from the cached index).
|
||||
- `GET /api/stats` — total file count, total size, page title, and when the
|
||||
index was last rebuilt.
|
||||
- `GET /files/<relative/path>` — streams the file's contents from disk
|
||||
(supports Range requests, conditional GET, and does not buffer the file
|
||||
in memory).
|
||||
|
||||
Any other path is served the SPA shell, which reads the current URL and
|
||||
drives navigation through the API above.
|
||||
|
||||
## Architecture notes
|
||||
|
||||
- `internal/index` builds a full recursive snapshot of `ROOT_DIR` with
|
||||
`filepath.WalkDir`, stores it behind an `atomic.Pointer`, and swaps in a
|
||||
fresh snapshot on each rebuild — reads never block on rebuilds.
|
||||
- `internal/server` wires the Gin routes, the vhost guard, and the
|
||||
streaming file handler.
|
||||
- `web/` embeds the `frontend/` directory (`index.html`, `assets/`) via
|
||||
`go:embed` so the compiled binary is fully self-contained.
|
||||
44
go.mod
Normal file
44
go.mod
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
module jonasled.dev/jonasled/pretty-directorylist
|
||||
|
||||
go 1.26.5
|
||||
|
||||
require (
|
||||
github.com/fsnotify/fsnotify v1.10.1
|
||||
github.com/gin-gonic/gin v1.12.0
|
||||
github.com/joho/godotenv v1.5.1
|
||||
jonasled.dev/jonasled/go-libs v0.0.3
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/bytedance/gopkg v0.1.3 // indirect
|
||||
github.com/bytedance/sonic v1.15.0 // indirect
|
||||
github.com/bytedance/sonic/loader v0.5.0 // indirect
|
||||
github.com/cloudwego/base64x v0.1.6 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.12 // indirect
|
||||
github.com/gin-contrib/sse v1.1.0 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-playground/validator/v10 v10.30.1 // indirect
|
||||
github.com/goccy/go-json v0.10.5 // indirect
|
||||
github.com/goccy/go-yaml v1.19.2 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
|
||||
github.com/quic-go/qpack v0.6.0 // indirect
|
||||
github.com/quic-go/quic-go v0.59.0 // indirect
|
||||
github.com/sirupsen/logrus v1.9.3 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.3.1 // indirect
|
||||
go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect
|
||||
golang.org/x/arch v0.22.0 // indirect
|
||||
golang.org/x/crypto v0.48.0 // indirect
|
||||
golang.org/x/net v0.51.0 // indirect
|
||||
golang.org/x/sys v0.41.0 // indirect
|
||||
golang.org/x/text v0.34.0 // indirect
|
||||
google.golang.org/protobuf v1.36.10 // indirect
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
|
||||
)
|
||||
101
go.sum
Normal file
101
go.sum
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M=
|
||||
github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM=
|
||||
github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE=
|
||||
github.com/bytedance/sonic v1.15.0/go.mod h1:tFkWrPz0/CUCLEF4ri4UkHekCIcdnkqXw9VduqpJh0k=
|
||||
github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiDd5VjlgE=
|
||||
github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo=
|
||||
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
|
||||
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho=
|
||||
github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo=
|
||||
github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw=
|
||||
github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
|
||||
github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
|
||||
github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
|
||||
github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8=
|
||||
github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc=
|
||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w=
|
||||
github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM=
|
||||
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
|
||||
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
||||
github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=
|
||||
github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
||||
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
|
||||
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
|
||||
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
|
||||
github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw=
|
||||
github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU=
|
||||
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
|
||||
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||
github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY=
|
||||
github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
|
||||
go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE=
|
||||
go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0=
|
||||
go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=
|
||||
go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=
|
||||
golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI=
|
||||
golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=
|
||||
golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=
|
||||
golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=
|
||||
golang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=
|
||||
golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=
|
||||
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
|
||||
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=
|
||||
golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=
|
||||
google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE=
|
||||
google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
jonasled.dev/jonasled/go-libs v0.0.3 h1:2Tg1pYJMufBMPkyYVVAvsUJe/R+TRRtRVW9MCbc24bM=
|
||||
jonasled.dev/jonasled/go-libs v0.0.3/go.mod h1:E8Sev4obR0x6y7x0HaIN1tImeLnVJgwJXt++jzTwiFM=
|
||||
58
internal/config/config.go
Normal file
58
internal/config/config.go
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Config holds all runtime configuration, sourced from environment variables.
|
||||
type Config struct {
|
||||
// ListenAddr is the address the HTTP server binds to, e.g. ":8080".
|
||||
ListenAddr string
|
||||
// RootDir is the directory on disk that gets listed and served.
|
||||
RootDir string
|
||||
// PageTitle is shown in the frontend header and browser tab.
|
||||
PageTitle string
|
||||
// FilesVHost, if set, restricts the directory listing app to requests
|
||||
// whose Host header matches this value. Other hosts get a 404.
|
||||
FilesVHost string
|
||||
// CacheRefreshInterval controls how often the in-memory file index is
|
||||
// rebuilt from disk.
|
||||
CacheRefreshInterval time.Duration
|
||||
// MaxSearchResults caps the number of results returned by /api/search.
|
||||
MaxSearchResults int
|
||||
// GinMode is passed to gin.SetMode ("release", "debug", "test").
|
||||
GinMode string
|
||||
}
|
||||
|
||||
func getEnv(key, fallback string) string {
|
||||
if v, ok := os.LookupEnv(key); ok && v != "" {
|
||||
return v
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func getEnvInt(key string, fallback int) int {
|
||||
if v, ok := os.LookupEnv(key); ok && v != "" {
|
||||
if i, err := strconv.Atoi(v); err == nil {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
// Load builds a Config from environment variables, applying sane defaults.
|
||||
func Load() Config {
|
||||
refreshSeconds := getEnvInt("CACHE_REFRESH_INTERVAL_SECONDS", 30)
|
||||
|
||||
return Config{
|
||||
ListenAddr: getEnv("LISTEN_ADDR", ":8080"),
|
||||
RootDir: getEnv("ROOT_DIR", "./data"),
|
||||
PageTitle: getEnv("PAGE_TITLE", "File List"),
|
||||
FilesVHost: getEnv("FILES_VHOST", ""),
|
||||
CacheRefreshInterval: time.Duration(refreshSeconds) * time.Second,
|
||||
MaxSearchResults: getEnvInt("MAX_SEARCH_RESULTS", 500),
|
||||
GinMode: getEnv("GIN_MODE", "release"),
|
||||
}
|
||||
}
|
||||
234
internal/index/index.go
Normal file
234
internal/index/index.go
Normal file
|
|
@ -0,0 +1,234 @@
|
|||
// Package index maintains an in-memory, periodically refreshed snapshot of
|
||||
// the served directory tree so that directory listings and recursive
|
||||
// searches stay fast even with several thousand files, without touching
|
||||
// disk on every request.
|
||||
package index
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/fsnotify/fsnotify"
|
||||
"jonasled.dev/jonasled/go-libs/log"
|
||||
)
|
||||
|
||||
// Entry describes a single file or directory relative to the root.
|
||||
type Entry struct {
|
||||
Name string `json:"name"`
|
||||
Path string `json:"path"` // slash-separated, relative to root, no leading slash
|
||||
IsDir bool `json:"isDir"`
|
||||
Size int64 `json:"size"`
|
||||
ModTime time.Time `json:"modTime"`
|
||||
}
|
||||
|
||||
// snapshot is one immutable, fully-built view of the tree.
|
||||
type snapshot struct {
|
||||
// byDir maps a directory's relative path ("" for root) to its direct children.
|
||||
byDir map[string][]Entry
|
||||
// flat is every file and directory in the tree, used for recursive search.
|
||||
flat []Entry
|
||||
fileCount int
|
||||
totalSize int64
|
||||
builtAt time.Time
|
||||
}
|
||||
|
||||
// Index owns the current snapshot and keeps it fresh.
|
||||
type Index struct {
|
||||
root string
|
||||
current atomic.Pointer[snapshot]
|
||||
}
|
||||
|
||||
// New creates an Index rooted at root and performs an initial build.
|
||||
func New(root string) *Index {
|
||||
idx := &Index{root: root}
|
||||
idx.Rebuild()
|
||||
return idx
|
||||
}
|
||||
|
||||
// Rebuild walks the root directory and atomically swaps in a new snapshot.
|
||||
// It never blocks readers: they keep using the previous snapshot until the
|
||||
// new one is ready.
|
||||
func (idx *Index) Rebuild() {
|
||||
start := time.Now()
|
||||
snap := &snapshot{
|
||||
byDir: make(map[string][]Entry),
|
||||
}
|
||||
|
||||
err := filepath.WalkDir(idx.root, func(p string, d fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
// Skip entries we can't stat (permission errors, races with
|
||||
// deletion, etc.) instead of failing the whole walk.
|
||||
return nil
|
||||
}
|
||||
if p == idx.root {
|
||||
return nil
|
||||
}
|
||||
|
||||
rel, err := filepath.Rel(idx.root, p)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
rel = filepath.ToSlash(rel)
|
||||
|
||||
info, err := d.Info()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
entry := Entry{
|
||||
Name: d.Name(),
|
||||
Path: rel,
|
||||
IsDir: d.IsDir(),
|
||||
ModTime: info.ModTime(),
|
||||
}
|
||||
if !d.IsDir() {
|
||||
entry.Size = info.Size()
|
||||
snap.fileCount++
|
||||
snap.totalSize += entry.Size
|
||||
}
|
||||
|
||||
parent := path.Dir(rel)
|
||||
if parent == "." {
|
||||
parent = ""
|
||||
}
|
||||
snap.byDir[parent] = append(snap.byDir[parent], entry)
|
||||
snap.flat = append(snap.flat, entry)
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
log.Log.WithError(err).Error("index: walk failed")
|
||||
}
|
||||
|
||||
for k := range snap.byDir {
|
||||
children := snap.byDir[k]
|
||||
sort.Slice(children, func(i, j int) bool {
|
||||
if children[i].IsDir != children[j].IsDir {
|
||||
return children[i].IsDir
|
||||
}
|
||||
return strings.ToLower(children[i].Name) < strings.ToLower(children[j].Name)
|
||||
})
|
||||
snap.byDir[k] = children
|
||||
}
|
||||
|
||||
snap.builtAt = time.Now()
|
||||
idx.current.Store(snap)
|
||||
log.Log.WithFields(map[string]interface{}{
|
||||
"files": snap.fileCount,
|
||||
"totalSize": snap.totalSize,
|
||||
"duration": time.Since(start).String(),
|
||||
}).Debug("index: rebuilt")
|
||||
}
|
||||
|
||||
// StartAutoRefresh rebuilds the index on a fixed interval and, best-effort,
|
||||
// as soon as fsnotify observes a change under root. It runs until stop is
|
||||
// closed.
|
||||
func (idx *Index) StartAutoRefresh(interval time.Duration, stop <-chan struct{}) {
|
||||
watcher, err := fsnotify.NewWatcher()
|
||||
if err != nil {
|
||||
log.Log.WithError(err).Warn("index: fsnotify unavailable, falling back to interval-only refresh")
|
||||
watcher = nil
|
||||
}
|
||||
if watcher != nil {
|
||||
idx.addWatchesRecursive(watcher)
|
||||
}
|
||||
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
|
||||
var debounce *time.Timer
|
||||
debounceCh := make(chan struct{}, 1)
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
if watcher != nil {
|
||||
watcher.Close()
|
||||
}
|
||||
return
|
||||
case <-ticker.C:
|
||||
idx.Rebuild()
|
||||
if watcher != nil {
|
||||
idx.addWatchesRecursive(watcher)
|
||||
}
|
||||
case ev, ok := <-watcherEvents(watcher):
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
_ = ev
|
||||
if debounce == nil {
|
||||
debounce = time.AfterFunc(500*time.Millisecond, func() {
|
||||
select {
|
||||
case debounceCh <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
})
|
||||
} else {
|
||||
debounce.Reset(500 * time.Millisecond)
|
||||
}
|
||||
case <-debounceCh:
|
||||
idx.Rebuild()
|
||||
if watcher != nil {
|
||||
idx.addWatchesRecursive(watcher)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func watcherEvents(w *fsnotify.Watcher) chan fsnotify.Event {
|
||||
if w == nil {
|
||||
return nil
|
||||
}
|
||||
return w.Events
|
||||
}
|
||||
|
||||
func (idx *Index) addWatchesRecursive(watcher *fsnotify.Watcher) {
|
||||
_ = filepath.WalkDir(idx.root, func(p string, d fs.DirEntry, err error) error {
|
||||
if err != nil || !d.IsDir() {
|
||||
return nil
|
||||
}
|
||||
// AddWatch is a no-op if the path is already watched.
|
||||
_ = watcher.Add(p)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// List returns the direct children of dir (relative path, "" for root).
|
||||
// The second return value is false if dir does not exist in the index.
|
||||
func (idx *Index) List(dir string) ([]Entry, bool) {
|
||||
snap := idx.current.Load()
|
||||
dir = strings.Trim(path.Clean("/"+dir), "/")
|
||||
entries, ok := snap.byDir[dir]
|
||||
return entries, ok || dir == ""
|
||||
}
|
||||
|
||||
// Search returns up to limit entries anywhere in the tree whose name
|
||||
// contains query (case-insensitive).
|
||||
func (idx *Index) Search(query string, limit int) []Entry {
|
||||
snap := idx.current.Load()
|
||||
query = strings.ToLower(strings.TrimSpace(query))
|
||||
if query == "" {
|
||||
return nil
|
||||
}
|
||||
results := make([]Entry, 0, limit)
|
||||
for _, e := range snap.flat {
|
||||
if strings.Contains(strings.ToLower(e.Name), query) {
|
||||
results = append(results, e)
|
||||
if len(results) >= limit {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
// Stats returns aggregate counters for the current snapshot.
|
||||
func (idx *Index) Stats() (fileCount int, totalSize int64, builtAt time.Time) {
|
||||
snap := idx.current.Load()
|
||||
return snap.fileCount, snap.totalSize, snap.builtAt
|
||||
}
|
||||
143
internal/server/handlers.go
Normal file
143
internal/server/handlers.go
Normal file
|
|
@ -0,0 +1,143 @@
|
|||
package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"jonasled.dev/jonasled/pretty-directorylist/internal/index"
|
||||
)
|
||||
|
||||
// nonNilEntries ensures the JSON response contains [] instead of null when
|
||||
// a directory is empty or a search has no hits.
|
||||
func nonNilEntries(e []index.Entry) []index.Entry {
|
||||
if e == nil {
|
||||
return []index.Entry{}
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
type dirResponse struct {
|
||||
Path string `json:"path"`
|
||||
Parent *string `json:"parent"`
|
||||
Entries interface{} `json:"entries"`
|
||||
}
|
||||
|
||||
func (s *Server) handleListDir(c *gin.Context) {
|
||||
dir := c.Query("path")
|
||||
|
||||
entries, ok := s.idx.List(dir)
|
||||
if !ok {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "directory not found"})
|
||||
return
|
||||
}
|
||||
|
||||
clean := strings.Trim(filepath.ToSlash(filepath.Clean("/"+dir)), "/")
|
||||
|
||||
var parent *string
|
||||
if clean != "" {
|
||||
p := strings.Trim(filepath.ToSlash(filepath.Dir(clean)), "/")
|
||||
if p == "." {
|
||||
p = ""
|
||||
}
|
||||
parent = &p
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, dirResponse{Path: clean, Parent: parent, Entries: nonNilEntries(entries)})
|
||||
}
|
||||
|
||||
func (s *Server) handleSearch(c *gin.Context) {
|
||||
q := c.Query("q")
|
||||
limit := s.cfg.MaxSearchResults
|
||||
if l, err := strconv.Atoi(c.Query("limit")); err == nil && l > 0 && l < limit {
|
||||
limit = l
|
||||
}
|
||||
|
||||
results := s.idx.Search(q, limit)
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"query": q,
|
||||
"count": len(results),
|
||||
"results": nonNilEntries(results),
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleStats(c *gin.Context) {
|
||||
fileCount, totalSize, builtAt := s.idx.Stats()
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"pageTitle": s.cfg.PageTitle,
|
||||
"fileCount": fileCount,
|
||||
"totalSize": totalSize,
|
||||
"indexedAt": builtAt,
|
||||
})
|
||||
}
|
||||
|
||||
// handleServeFile streams a file straight from disk via http.ServeContent,
|
||||
// which handles Range/If-Modified-Since and never buffers the whole file
|
||||
// in memory - it reads directly from the *os.File.
|
||||
func (s *Server) handleServeFile(c *gin.Context) {
|
||||
reqPath := strings.TrimPrefix(c.Param("path"), "/")
|
||||
|
||||
fullPath, err := s.resolvePath(reqPath)
|
||||
if err != nil {
|
||||
c.AbortWithStatus(http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
info, err := os.Stat(fullPath)
|
||||
if err != nil {
|
||||
c.AbortWithStatus(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
if info.IsDir() {
|
||||
c.AbortWithStatus(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
f, err := os.Open(fullPath)
|
||||
if err != nil {
|
||||
c.AbortWithStatus(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
c.Header("Content-Disposition", "inline; filename=\""+info.Name()+"\"")
|
||||
http.ServeContent(c.Writer, c.Request, info.Name(), info.ModTime(), f)
|
||||
}
|
||||
|
||||
// resolvePath joins reqPath onto the configured root and rejects any
|
||||
// traversal outside of it.
|
||||
func (s *Server) resolvePath(reqPath string) (string, error) {
|
||||
cleaned := filepath.Clean("/" + reqPath)
|
||||
full := filepath.Join(s.cfg.RootDir, cleaned)
|
||||
|
||||
rootAbs, err := filepath.Abs(s.cfg.RootDir)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
fullAbs, err := filepath.Abs(full)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if fullAbs != rootAbs && !strings.HasPrefix(fullAbs, rootAbs+string(os.PathSeparator)) {
|
||||
return "", os.ErrPermission
|
||||
}
|
||||
return fullAbs, nil
|
||||
}
|
||||
|
||||
func (s *Server) handleSPA(c *gin.Context) {
|
||||
p := c.Request.URL.Path
|
||||
if strings.HasPrefix(p, "/api/") || strings.HasPrefix(p, "/files/") || strings.HasPrefix(p, "/assets/") {
|
||||
c.AbortWithStatus(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
c.Status(http.StatusOK)
|
||||
c.Header("Content-Type", "text/html; charset=utf-8")
|
||||
_ = s.tmpl.Execute(c.Writer, gin.H{
|
||||
"PageTitle": s.cfg.PageTitle,
|
||||
})
|
||||
}
|
||||
83
internal/server/server.go
Normal file
83
internal/server/server.go
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
// Package server wires up the gin router: the JSON API used by the
|
||||
// single-page frontend, the streaming file endpoint, and the SPA shell.
|
||||
package server
|
||||
|
||||
import (
|
||||
"html/template"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"jonasled.dev/jonasled/pretty-directorylist/internal/config"
|
||||
"jonasled.dev/jonasled/pretty-directorylist/internal/index"
|
||||
)
|
||||
|
||||
// Server bundles the dependencies needed to build the gin engine.
|
||||
type Server struct {
|
||||
cfg config.Config
|
||||
idx *index.Index
|
||||
tmpl *template.Template
|
||||
files fs.FS // embedded frontend/assets, served at /assets
|
||||
}
|
||||
|
||||
// New builds the Server. frontendFS is the embedded "frontend" directory
|
||||
// (containing index.html and assets/).
|
||||
func New(cfg config.Config, idx *index.Index, frontendFS fs.FS) (*Server, error) {
|
||||
tmpl, err := template.ParseFS(frontendFS, "index.html")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
assets, err := fs.Sub(frontendFS, "assets")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &Server{cfg: cfg, idx: idx, tmpl: tmpl, files: assets}, nil
|
||||
}
|
||||
|
||||
// Engine builds and returns the configured gin.Engine.
|
||||
func (s *Server) Engine() *gin.Engine {
|
||||
gin.SetMode(s.cfg.GinMode)
|
||||
r := gin.New()
|
||||
r.Use(gin.Recovery(), gin.LoggerWithWriter(gin.DefaultWriter, "/healthz"))
|
||||
|
||||
if s.cfg.FilesVHost != "" {
|
||||
r.Use(s.vhostGuard)
|
||||
}
|
||||
|
||||
r.GET("/healthz", func(c *gin.Context) { c.String(http.StatusOK, "ok") })
|
||||
|
||||
api := r.Group("/api")
|
||||
{
|
||||
api.GET("/dir", s.handleListDir)
|
||||
api.GET("/search", s.handleSearch)
|
||||
api.GET("/stats", s.handleStats)
|
||||
}
|
||||
|
||||
r.GET("/files/*path", s.handleServeFile)
|
||||
|
||||
r.StaticFS("/assets", http.FS(s.files))
|
||||
|
||||
// Everything else is the SPA shell; client-side JS reads the path from
|
||||
// window.location and drives navigation through the /api endpoints.
|
||||
r.NoRoute(s.handleSPA)
|
||||
r.GET("/", s.handleSPA)
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
// vhostGuard restricts every route to requests whose Host header matches
|
||||
// the configured FilesVHost.
|
||||
func (s *Server) vhostGuard(c *gin.Context) {
|
||||
host := c.Request.Host
|
||||
if idx := strings.LastIndex(host, ":"); idx != -1 {
|
||||
host = host[:idx]
|
||||
}
|
||||
if !strings.EqualFold(host, s.cfg.FilesVHost) {
|
||||
c.AbortWithStatus(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
52
main.go
Normal file
52
main.go
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
_ "github.com/joho/godotenv/autoload"
|
||||
"jonasled.dev/jonasled/go-libs/log"
|
||||
"jonasled.dev/jonasled/pretty-directorylist/internal/config"
|
||||
"jonasled.dev/jonasled/pretty-directorylist/internal/index"
|
||||
"jonasled.dev/jonasled/pretty-directorylist/internal/server"
|
||||
"jonasled.dev/jonasled/pretty-directorylist/web"
|
||||
)
|
||||
|
||||
func main() {
|
||||
log.Init()
|
||||
|
||||
cfg := config.Load()
|
||||
|
||||
idx := index.New(cfg.RootDir)
|
||||
stop := make(chan struct{})
|
||||
go idx.StartAutoRefresh(cfg.CacheRefreshInterval, stop)
|
||||
|
||||
frontendFS, err := fs.Sub(web.Frontend(), "frontend")
|
||||
if err != nil {
|
||||
log.Log.WithError(err).Fatal("failed to load embedded frontend")
|
||||
}
|
||||
|
||||
srv, err := server.New(cfg, idx, frontendFS)
|
||||
if err != nil {
|
||||
log.Log.WithError(err).Fatal("failed to initialize server")
|
||||
}
|
||||
|
||||
engine := srv.Engine()
|
||||
|
||||
log.Log.WithField("addr", cfg.ListenAddr).WithField("root", cfg.RootDir).Info("starting server")
|
||||
|
||||
go func() {
|
||||
if err := engine.Run(cfg.ListenAddr); err != nil {
|
||||
log.Log.WithError(err).Fatal("server stopped unexpectedly")
|
||||
}
|
||||
}()
|
||||
|
||||
quit := make(chan os.Signal, 1)
|
||||
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
|
||||
<-quit
|
||||
|
||||
close(stop)
|
||||
log.Log.Info("shutting down")
|
||||
}
|
||||
14
web/embed.go
Normal file
14
web/embed.go
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
// Package web embeds the frontend (SPA shell, CSS, JS) into the compiled
|
||||
// binary so the Docker image only needs the single Go executable.
|
||||
package web
|
||||
|
||||
import "embed"
|
||||
|
||||
//go:embed frontend/index.html frontend/assets
|
||||
var FrontendFS embed.FS
|
||||
|
||||
// Frontend returns the embedded frontend rooted at "frontend", i.e. the
|
||||
// returned fs.FS has index.html and assets/ directly at its root.
|
||||
func Frontend() embed.FS {
|
||||
return FrontendFS
|
||||
}
|
||||
224
web/frontend/assets/app.js
Normal file
224
web/frontend/assets/app.js
Normal file
|
|
@ -0,0 +1,224 @@
|
|||
(function () {
|
||||
"use strict";
|
||||
|
||||
var state = {
|
||||
sortColumn: "name",
|
||||
sortAscending: true,
|
||||
currentPath: "",
|
||||
currentEntries: [],
|
||||
searchMode: false,
|
||||
};
|
||||
|
||||
var els = {
|
||||
listing: document.getElementById("listing"),
|
||||
search: document.getElementById("search"),
|
||||
breadcrumbs: document.getElementById("breadcrumbs"),
|
||||
emptyState: document.getElementById("empty-state"),
|
||||
statFileCount: document.getElementById("stat-filecount"),
|
||||
statTotalSize: document.getElementById("stat-totalsize"),
|
||||
};
|
||||
|
||||
function humanSize(bytes, decimals) {
|
||||
decimals = decimals === undefined ? 2 : decimals;
|
||||
if (bytes === 0 || bytes === undefined || bytes === null) return "0 B";
|
||||
var units = ["B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
|
||||
var factor = Math.min(units.length - 1, Math.floor(Math.log(bytes) / Math.log(1024)));
|
||||
return (bytes / Math.pow(1024, factor)).toFixed(decimals) + " " + units[factor];
|
||||
}
|
||||
|
||||
function formatDate(iso) {
|
||||
if (!iso) return "";
|
||||
var d = new Date(iso);
|
||||
if (isNaN(d.getTime())) return "";
|
||||
return d.toLocaleString();
|
||||
}
|
||||
|
||||
function pathFromLocation() {
|
||||
return decodeURIComponent(window.location.pathname).replace(/^\/+/, "").replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
function apiUrl(base, params) {
|
||||
var url = new URL(base, window.location.origin);
|
||||
Object.keys(params || {}).forEach(function (k) {
|
||||
if (params[k] !== undefined && params[k] !== null && params[k] !== "") {
|
||||
url.searchParams.set(k, params[k]);
|
||||
}
|
||||
});
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
function sortEntries(entries) {
|
||||
var col = state.sortColumn;
|
||||
var asc = state.sortAscending;
|
||||
var sorted = entries.slice();
|
||||
sorted.sort(function (a, b) {
|
||||
// directories always float to the top, matching typical file browsers
|
||||
if (a.isDir !== b.isDir) return a.isDir ? -1 : 1;
|
||||
|
||||
var av = a[col];
|
||||
var bv = b[col];
|
||||
var cmp;
|
||||
if (typeof av === "number" && typeof bv === "number") {
|
||||
cmp = av - bv;
|
||||
} else {
|
||||
cmp = String(av).toLowerCase().localeCompare(String(bv).toLowerCase());
|
||||
}
|
||||
return asc ? cmp : -cmp;
|
||||
});
|
||||
return sorted;
|
||||
}
|
||||
|
||||
function renderBreadcrumbs(path) {
|
||||
els.breadcrumbs.innerHTML = "";
|
||||
var rootLink = document.createElement("a");
|
||||
rootLink.href = "/";
|
||||
rootLink.textContent = "Home";
|
||||
rootLink.addEventListener("click", onNavClick);
|
||||
els.breadcrumbs.appendChild(rootLink);
|
||||
|
||||
if (!path) return;
|
||||
|
||||
var parts = path.split("/");
|
||||
var acc = "";
|
||||
parts.forEach(function (part) {
|
||||
acc = acc ? acc + "/" + part : part;
|
||||
els.breadcrumbs.appendChild(document.createTextNode(" / "));
|
||||
var a = document.createElement("a");
|
||||
a.href = "/" + acc;
|
||||
a.textContent = part;
|
||||
a.addEventListener("click", onNavClick);
|
||||
els.breadcrumbs.appendChild(a);
|
||||
});
|
||||
}
|
||||
|
||||
function renderRows(entries, opts) {
|
||||
opts = opts || {};
|
||||
els.listing.innerHTML = "";
|
||||
els.emptyState.hidden = entries.length !== 0;
|
||||
|
||||
entries.forEach(function (item) {
|
||||
var row = document.createElement("tr");
|
||||
|
||||
var nameCell = document.createElement("td");
|
||||
var link = document.createElement("a");
|
||||
var displayName = opts.showFullPath ? item.path : item.name;
|
||||
|
||||
if (item.isDir) {
|
||||
link.href = "/" + item.path;
|
||||
link.textContent = "📁 " + displayName;
|
||||
link.addEventListener("click", onNavClick);
|
||||
} else {
|
||||
link.href = "/files/" + item.path;
|
||||
link.textContent = "📄 " + displayName;
|
||||
link.setAttribute("download", item.name);
|
||||
}
|
||||
nameCell.appendChild(link);
|
||||
row.appendChild(nameCell);
|
||||
|
||||
var sizeCell = document.createElement("td");
|
||||
sizeCell.textContent = item.isDir ? "-" : humanSize(item.size);
|
||||
row.appendChild(sizeCell);
|
||||
|
||||
var modCell = document.createElement("td");
|
||||
modCell.textContent = formatDate(item.modTime);
|
||||
row.appendChild(modCell);
|
||||
|
||||
els.listing.appendChild(row);
|
||||
});
|
||||
}
|
||||
|
||||
function renderCurrentView() {
|
||||
var entries = state.searchMode
|
||||
? state.currentEntries
|
||||
: state.currentEntries.filter(function (item) {
|
||||
return item.name.toLowerCase().indexOf(els.search.value.toLowerCase()) > -1;
|
||||
});
|
||||
renderRows(sortEntries(entries), { showFullPath: state.searchMode });
|
||||
}
|
||||
|
||||
function loadStats() {
|
||||
fetch(apiUrl("/api/stats")).then(function (r) { return r.json(); }).then(function (data) {
|
||||
els.statFileCount.textContent = data.fileCount;
|
||||
els.statTotalSize.textContent = humanSize(data.totalSize);
|
||||
}).catch(function () {});
|
||||
}
|
||||
|
||||
function loadDirectory(path, pushHistory) {
|
||||
state.searchMode = false;
|
||||
els.search.value = "";
|
||||
|
||||
fetch(apiUrl("/api/dir", { path: path }))
|
||||
.then(function (r) {
|
||||
if (!r.ok) throw new Error("not found");
|
||||
return r.json();
|
||||
})
|
||||
.then(function (data) {
|
||||
state.currentPath = data.path;
|
||||
state.currentEntries = data.entries || [];
|
||||
renderBreadcrumbs(data.path);
|
||||
renderCurrentView();
|
||||
|
||||
if (pushHistory) {
|
||||
var target = "/" + data.path;
|
||||
if (window.location.pathname !== target) {
|
||||
window.history.pushState({ path: data.path }, "", target === "/" ? "/" : target);
|
||||
}
|
||||
}
|
||||
})
|
||||
.catch(function () {
|
||||
els.listing.innerHTML = "";
|
||||
els.emptyState.hidden = false;
|
||||
els.emptyState.textContent = "Directory not found.";
|
||||
});
|
||||
}
|
||||
|
||||
function runSearch(query) {
|
||||
if (!query) {
|
||||
loadDirectory(state.currentPath, false);
|
||||
return;
|
||||
}
|
||||
state.searchMode = true;
|
||||
fetch(apiUrl("/api/search", { q: query }))
|
||||
.then(function (r) { return r.json(); })
|
||||
.then(function (data) {
|
||||
state.currentEntries = data.results || [];
|
||||
renderCurrentView();
|
||||
});
|
||||
}
|
||||
|
||||
function onNavClick(e) {
|
||||
e.preventDefault();
|
||||
var href = e.currentTarget.getAttribute("href");
|
||||
var path = href.replace(/^\/+/, "");
|
||||
loadDirectory(path, true);
|
||||
}
|
||||
|
||||
var searchDebounce;
|
||||
els.search.addEventListener("input", function () {
|
||||
clearTimeout(searchDebounce);
|
||||
var query = els.search.value;
|
||||
searchDebounce = setTimeout(function () {
|
||||
runSearch(query.trim());
|
||||
}, 150);
|
||||
});
|
||||
|
||||
document.querySelectorAll("th span[data-sort]").forEach(function (span) {
|
||||
span.addEventListener("click", function () {
|
||||
var col = span.getAttribute("data-sort");
|
||||
if (state.sortColumn === col) {
|
||||
state.sortAscending = !state.sortAscending;
|
||||
} else {
|
||||
state.sortColumn = col;
|
||||
state.sortAscending = true;
|
||||
}
|
||||
renderCurrentView();
|
||||
});
|
||||
});
|
||||
|
||||
window.addEventListener("popstate", function () {
|
||||
loadDirectory(pathFromLocation(), false);
|
||||
});
|
||||
|
||||
loadStats();
|
||||
loadDirectory(pathFromLocation(), false);
|
||||
})();
|
||||
119
web/frontend/assets/style.css
Normal file
119
web/frontend/assets/style.css
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
*,*::before,*::after{box-sizing:border-box;}
|
||||
*{margin:0;padding:0;}
|
||||
|
||||
body {
|
||||
background-color: black;
|
||||
min-height: 100vh;
|
||||
color: white;
|
||||
font-family: 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
|
||||
}
|
||||
|
||||
.content {
|
||||
margin: 3rem auto;
|
||||
max-width: 1100px;
|
||||
padding: 0 2rem;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 5rem;
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
h3 {
|
||||
margin-top: 0;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
input:focus {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
input {
|
||||
display: inline-block;
|
||||
font-weight: 400;
|
||||
line-height: 1.5;
|
||||
color: #668295;
|
||||
background-color: transparent;
|
||||
background-clip: padding-box;
|
||||
border: 1px solid #B7C4CD;
|
||||
border-radius: 4px;
|
||||
vertical-align: middle;
|
||||
height: calc(1.8rem + 1.25rem + 2px);
|
||||
width: 100%;
|
||||
padding: 0.625rem calc(1.25rem + .5rem);
|
||||
font-size: 1.2rem;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
|
||||
input:focus {
|
||||
outline: none;
|
||||
box-shadow: 0 0 0 0.125em rgba(183, 196, 205, 0.5);
|
||||
}
|
||||
|
||||
input:hover {
|
||||
border-color: #60798b;
|
||||
}
|
||||
|
||||
a {
|
||||
color: #bbbbbb;
|
||||
text-decoration: none;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
a:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
h3 a {
|
||||
color: white;
|
||||
}
|
||||
|
||||
td {
|
||||
padding: 5px;
|
||||
}
|
||||
|
||||
table {
|
||||
border-collapse: collapse;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
tr:nth-child(even) {
|
||||
background-color: #2b2b2b;
|
||||
}
|
||||
|
||||
th {
|
||||
text-align: left;
|
||||
padding: 10px;
|
||||
background-color: #566E7E;
|
||||
}
|
||||
|
||||
th span {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
|
||||
p {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.breadcrumbs {
|
||||
margin-bottom: 10px;
|
||||
font-size: 1rem;
|
||||
color: #bbbbbb;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.breadcrumbs a {
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
color: #888888;
|
||||
padding: 20px 0;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
tbody tr:hover {
|
||||
background-color: #3a3a3a;
|
||||
}
|
||||
41
web/frontend/index.html
Normal file
41
web/frontend/index.html
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>{{ .PageTitle }}</title>
|
||||
<link rel="stylesheet" href="/assets/style.css">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="content">
|
||||
<h1>{{ .PageTitle }}</h1>
|
||||
<h3>Provided by <a href="https://jonasled.de">Jonas Leder</a></h3>
|
||||
<p>
|
||||
Total files: <span id="stat-filecount">-</span><br>
|
||||
Total size: <span id="stat-totalsize">-</span>
|
||||
<br>
|
||||
</p>
|
||||
<nav id="breadcrumbs" class="breadcrumbs"></nav>
|
||||
<div>
|
||||
<input type="text" id="search" placeholder="Search across all folders..." aria-label="Search across all folders">
|
||||
</div>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th><span data-sort="name">Name</span></th>
|
||||
<th><span data-sort="size">Size</span></th>
|
||||
<th><span data-sort="modTime">Modified</span></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="listing"></tbody>
|
||||
</table>
|
||||
<p id="empty-state" class="empty-state" hidden>No entries found.</p>
|
||||
</div>
|
||||
<script src="/assets/app.js"></script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
Loading…
Add table
Add a link
Reference in a new issue