From 5298b4bcfa27ac7ebc479b6c139f2da0f5ea3f59 Mon Sep 17 00:00:00 2001 From: Willy Kloucek Date: Mon, 13 Sep 2021 19:22:27 +0200 Subject: [PATCH] redirect to root when file not found --- .../redirect-invalid-links-to-oC-web.md | 5 +++ web/pkg/service/v0/service.go | 43 ++++++++++++++++--- 2 files changed, 42 insertions(+), 6 deletions(-) create mode 100644 changelog/unreleased/redirect-invalid-links-to-oC-web.md diff --git a/changelog/unreleased/redirect-invalid-links-to-oC-web.md b/changelog/unreleased/redirect-invalid-links-to-oC-web.md new file mode 100644 index 000000000..a7b17cf10 --- /dev/null +++ b/changelog/unreleased/redirect-invalid-links-to-oC-web.md @@ -0,0 +1,5 @@ +Enhancement: redirect invalid links to oC Web + +Invalid links (eg. https://foo.bar/index.php/apps/pdfviewer) will be redirect to ownCloud Web instead of displaying a blank page with a "not found" message. + +https://github.com/owncloud/ocis/pull/2493 diff --git a/web/pkg/service/v0/service.go b/web/pkg/service/v0/service.go index 7498fc809..ac022cb6d 100644 --- a/web/pkg/service/v0/service.go +++ b/web/pkg/service/v0/service.go @@ -133,14 +133,15 @@ func (p Web) Static(ttl int) http.HandlerFunc { if !strings.HasSuffix(rootWithSlash, "/") { rootWithSlash = rootWithSlash + "/" } - + assets := assets.New( + assets.Logger(p.logger), + assets.Config(p.config), + ) static := http.StripPrefix( rootWithSlash, - http.FileServer( - assets.New( - assets.Logger(p.logger), - assets.Config(p.config), - ), + interceptNotFound( + http.FileServer(assets), + rootWithSlash, ), ) @@ -182,3 +183,33 @@ func (p Web) Static(ttl int) http.HandlerFunc { static.ServeHTTP(w, r) } } + +func interceptNotFound(h http.Handler, root string) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + notFoundInterceptor := &NotFoundInterceptor{ResponseWriter: w} + h.ServeHTTP(notFoundInterceptor, r) + if notFoundInterceptor.status == http.StatusNotFound { + http.Redirect(w, r, root, http.StatusTemporaryRedirect) + // TODO: replace the redirect with a not found page containing a link to the Web UI + } + } +} + +type NotFoundInterceptor struct { + http.ResponseWriter + status int +} + +func (w *NotFoundInterceptor) WriteHeader(status int) { + w.status = status + if status != http.StatusNotFound { + w.ResponseWriter.WriteHeader(status) + } +} + +func (w *NotFoundInterceptor) Write(p []byte) (int, error) { + if w.status != http.StatusNotFound { + return w.ResponseWriter.Write(p) + } + return len(p), nil +}