diff --git a/.dockerignore b/.dockerignore index 6b68690..3d48687 100644 --- a/.dockerignore +++ b/.dockerignore @@ -15,7 +15,7 @@ test web/* !web/public !web/src -!web/build* +!web/dist* !web/package.json !web/yarn.lock !web/.yarnrc.yml @@ -24,3 +24,6 @@ web/* !web/postcss.config.js !web/tailwind.config.js !web/tsconfig.json +!web/index.html +!web/vite.config.ts +!web/build.go \ No newline at end of file diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b78125c..7bf35ef 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -38,8 +38,8 @@ jobs: - name: Upload web production build uses: actions/upload-artifact@v3 with: - name: web-build - path: web/build + name: web-dist + path: web/dist test: name: Test @@ -54,8 +54,8 @@ jobs: - name: Download web production build uses: actions/download-artifact@v3 with: - name: web-build - path: web/build + name: web-dist + path: web/dist # 1.20 is the last version to support Windows < 10, Server < 2016, and MacOS < 1.15. - name: Set up Go @@ -81,8 +81,8 @@ jobs: - name: Download web production build uses: actions/download-artifact@v3 with: - name: web-build - path: web/build + name: web-dist + path: web/dist # 1.20 is the last version to support Windows < 10, Server < 2016, and MacOS < 1.15. - name: Set up Go @@ -120,8 +120,8 @@ jobs: - name: Download web production build uses: actions/download-artifact@v3 with: - name: web-build - path: web/build + name: web-dist + path: web/dist # 1.20 is the last version to support Windows < 10, Server < 2016, and MacOS < 1.15. - name: Set up Go @@ -158,8 +158,8 @@ jobs: - name: Download web production build uses: actions/download-artifact@v3 with: - name: web-build - path: web/build + name: web-dist + path: web/dist - name: Login to GitHub Container Registry uses: docker/login-action@v2 @@ -195,4 +195,4 @@ jobs: VERSION=${{ fromJSON(steps.meta.outputs.json).labels['org.opencontainers.image.version'] }} REVISION=${{ github.event.pull_request.head.sha }} - name: Image digest - run: echo ${{ steps.docker_build.outputs.digest }} + run: echo ${{ steps.docker_build.outputs.digest }} \ No newline at end of file diff --git a/.gitignore b/.gitignore index eb45ae7..5a6a2e7 100644 --- a/.gitignore +++ b/.gitignore @@ -31,7 +31,7 @@ node_modules/ web/build bin/ log/ -dist/ +#dist/ .run/ # If needed, package-lock.json shall be added # manually using an explicit git add command. diff --git a/Dockerfile b/Dockerfile index b381fe2..7737544 100644 --- a/Dockerfile +++ b/Dockerfile @@ -25,7 +25,7 @@ RUN go mod download COPY . ./ -COPY --from=web-builder /web/build ./web/build +COPY --from=web-builder /web/dist ./web/dist COPY --from=web-builder /web/build.go ./web #ENV GOOS=linux @@ -55,4 +55,4 @@ COPY --from=app-builder /src/bin/autobrrctl /usr/local/bin/ EXPOSE 7474 ENTRYPOINT ["/usr/local/bin/autobrr", "--config", "/config"] -#CMD ["--config", "/config"] +#CMD ["--config", "/config"] \ No newline at end of file diff --git a/internal/http/server.go b/internal/http/server.go index 788c71b..5a5b577 100644 --- a/internal/http/server.go +++ b/internal/http/server.go @@ -2,7 +2,6 @@ package http import ( "fmt" - "io/fs" "net" "net/http" @@ -105,18 +104,8 @@ func (s Server) Handler() http.Handler { r.Use(c.Handler) - //r.Get("/", index) - //r.Get("/dashboard", dashboard) - - //handler := web.AssetHandler("/", "build") - encoder := encoder{} - - assets, _ := fs.Sub(web.Assets, "build/static") - r.HandleFunc("/static/*", func(w http.ResponseWriter, r *http.Request) { - fileSystem := http.StripPrefix("/static/", http.FileServer(http.FS(assets))) - fileSystem.ServeHTTP(w, r) - }) + web.RegisterHandler(r) r.Route("/api", func(r chi.Router) { r.Route("/auth", newAuthHandler(encoder, s.log, s.config.Config, s.cookieStore, s.authService).Routes) @@ -153,7 +142,7 @@ func (s Server) Handler() http.Handler { }) }) - //r.HandleFunc("/*", handler.ServeHTTP) + // serve the parsed index.html r.Get("/", s.index) r.Get("/*", s.index) diff --git a/web/.eslintrc.js b/web/.eslintrc.js index b504482..078f8b1 100644 --- a/web/.eslintrc.js +++ b/web/.eslintrc.js @@ -42,7 +42,7 @@ module.exports = { //"plugin:@typescript-eslint/recommended-requiring-type-checking", ], parserOptions: { - project: "tsconfig.json", + // project: "tsconfig.json", // This is needed so we can always point to the tsconfig.json // file relative to the current .eslintrc.js file. // Generally, a problem occurrs when "npm run lint" diff --git a/web/.gitignore b/web/.gitignore index d1422da..6d01f7b 100644 --- a/web/.gitignore +++ b/web/.gitignore @@ -31,7 +31,8 @@ node_modules/ web/build bin/ log/ -dist/ +dist/* +!dist/.gitkeep # If needed, package-lock.json shall be added # manually using an explicit git add command. package-lock.json diff --git a/web/README.md b/web/README.md index b58e0af..0203ea8 100644 --- a/web/README.md +++ b/web/README.md @@ -1,6 +1,6 @@ -# Getting Started with Create React App +# web -This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). +This project uses React built with Vite. ## Available Scripts @@ -14,33 +14,14 @@ Open [http://localhost:3000](http://localhost:3000) to view it in the browser. The page will reload if you make edits.\ You will also see any lint errors in the console. -### `yarn test` - -Launches the test runner in the interactive watch mode.\ -See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. - ### `yarn build` -Builds the app for production to the `build` folder.\ +Builds the app for production to the `dist` folder.\ It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.\ Your app is ready to be deployed! -See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. - -### `yarn eject` - -**Note: this is a one-way operation. Once you `eject`, you can’t go back!** - -If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. - -Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. - -You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. - ## Learn More -You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). - -To learn React, check out the [React documentation](https://reactjs.org/). +To learn React, check out the [React documentation](https://reactjs.org/). \ No newline at end of file diff --git a/web/build.go b/web/build.go index 0ab34b0..01192a1 100644 --- a/web/build.go +++ b/web/build.go @@ -2,47 +2,22 @@ package web import ( + "bytes" "embed" + "fmt" "html/template" "io" "io/fs" "net/http" "os" - "path" + "path/filepath" + + "github.com/go-chi/chi/v5" ) -//go:embed build -var Assets embed.FS - -// fsFunc is short-hand for constructing a http.FileSystem -// implementation -type fsFunc func(name string) (fs.File, error) - -func (f fsFunc) Open(name string) (fs.File, error) { - return f(name) -} - -// AssetHandler returns a http.Handler that will serve files from -// the Assets embed.FS. When locating a file, it will strip the given -// prefix from the request and prepend the root to the filesystem -// lookup: typical prefix might be /web/, and root would be build. -func AssetHandler(prefix, root string) http.Handler { - handler := fsFunc(func(name string) (fs.File, error) { - assetPath := path.Join(root, name) - - // If we can't find the asset, return the default index.html - // content - f, err := Assets.Open(assetPath) - if os.IsNotExist(err) { - return Assets.Open("build/index.html") - } - - // Otherwise, assume this is a legitimate request routed - // correctly - return f, err - }) - - return http.StripPrefix(prefix, http.FileServer(http.FS(handler))) +type defaultFS struct { + prefix string + fs fs.FS } type IndexParams struct { @@ -51,11 +26,109 @@ type IndexParams struct { BaseUrl string } +var ( + //go:embed all:dist + Dist embed.FS + + DistDirFS = MustSubFS(Dist, "dist") +) + +func (fs defaultFS) Open(name string) (fs.File, error) { + if fs.fs == nil { + return os.Open(name) + } + return fs.fs.Open(name) +} + +// MustSubFS creates sub FS from current filesystem or panic on failure. +// Panic happens when `fsRoot` contains invalid path according to `fs.ValidPath` rules. +// +// MustSubFS is helpful when dealing with `embed.FS` because for example `//go:embed assets/images` embeds files with +// paths including `assets/images` as their prefix. In that case use `fs := MustSubFS(fs, "rootDirectory") to +// create sub fs which uses necessary prefix for directory path. +func MustSubFS(currentFs fs.FS, fsRoot string) fs.FS { + subFs, err := subFS(currentFs, fsRoot) + if err != nil { + panic(fmt.Errorf("can not create sub FS, invalid root given, err: %w", err)) + } + return subFs +} + +func subFS(currentFs fs.FS, root string) (fs.FS, error) { + root = filepath.ToSlash(filepath.Clean(root)) // note: fs.FS operates only with slashes. `ToSlash` is necessary for Windows + if dFS, ok := currentFs.(*defaultFS); ok { + // we need to make exception for `defaultFS` instances as it interprets root prefix differently from fs.FS. + // fs.Fs.Open does not like relative paths ("./", "../") and absolute paths. + if !filepath.IsAbs(root) { + root = filepath.Join(dFS.prefix, root) + } + return &defaultFS{ + prefix: root, + fs: os.DirFS(root), + }, nil + } + return fs.Sub(currentFs, root) +} + +// FileFS registers a new route with path to serve a file from the provided file system. +func FileFS(r *chi.Mux, path, file string, filesystem fs.FS) { + r.Get(path, StaticFileHandler(file, filesystem)) +} + +// StaticFileHandler creates a handler function to serve a file from the provided file system. +func StaticFileHandler(file string, filesystem fs.FS) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + fsFile(w, r, file, filesystem) + } +} + +// StaticFS registers a new route with path prefix to serve static files from the provided file system. +func StaticFS(r *chi.Mux, pathPrefix string, filesystem fs.FS) { + r.Handle(pathPrefix+"*", http.StripPrefix(pathPrefix, http.FileServer(http.FS(filesystem)))) +} + +// fsFile is a helper function to serve a file from the provided file system. +func fsFile(w http.ResponseWriter, r *http.Request, file string, filesystem fs.FS) { + f, err := filesystem.Open(file) + if err != nil { + http.Error(w, "File not found", http.StatusNotFound) + return + } + defer f.Close() + + stat, err := f.Stat() + if err != nil { + http.Error(w, "File not found", http.StatusNotFound) + return + } + + data, err := io.ReadAll(f) + if err != nil { + http.Error(w, "Failed to read the file", http.StatusInternalServerError) + return + } + + reader := bytes.NewReader(data) + http.ServeContent(w, r, file, stat.ModTime(), reader) +} + +func RegisterHandler(c *chi.Mux) { + // Serve static files without a prefix + assets, _ := fs.Sub(DistDirFS, "assets") + static, _ := fs.Sub(DistDirFS, "static") + StaticFS(c, "/assets", assets) + StaticFS(c, "/static", static) + + c.Get("/*", func(w http.ResponseWriter, r *http.Request) { + // Serve index.html for unmatched routes + fsFile(w, r, "dist/index.html", Dist) + }) +} + func Index(w io.Writer, p IndexParams) error { return parseIndex().Execute(w, p) } func parseIndex() *template.Template { - return template.Must( - template.New("index.html").ParseFS(Assets, "build/index.html")) + return template.Must(template.New("index.html").ParseFS(Dist, "dist/index.html")) } diff --git a/web/dist/.gitkeep b/web/dist/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/web/public/index.html b/web/index.html similarity index 57% rename from web/public/index.html rename to web/index.html index 2b0e48a..bac14e6 100644 --- a/web/public/index.html +++ b/web/index.html @@ -2,32 +2,25 @@
- + - - + +