From 832a4ecd63eeff8c636a279dff206422bd9f4730 Mon Sep 17 00:00:00 2001 From: crystal Date: Fri, 20 May 2022 17:56:45 -0600 Subject: [PATCH] implement custom 404 pages --- server/upstream/upstream.go | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/server/upstream/upstream.go b/server/upstream/upstream.go index 88d3471..6edab84 100644 --- a/server/upstream/upstream.go +++ b/server/upstream/upstream.go @@ -22,6 +22,11 @@ var upstreamIndexPages = []string{ "index.html", } +// upstreamNotFoundPages lists pages that may be considered as custom 404 Not Found pages. +var upstreamNotFoundPages = []string{ + "404.html", +} + // Options provides various options for the upstream request. type Options struct { TargetOwner, @@ -124,6 +129,21 @@ func (o *Options) Upstream(ctx *fasthttp.RequestCtx, giteaRoot, giteaAPIToken st } } ctx.Response.SetStatusCode(fasthttp.StatusNotFound) + if o.TryIndexPages { + // copy the o struct & try if a not found page exists + optionsForNotFoundPages := *o + optionsForNotFoundPages.TryIndexPages = false + optionsForNotFoundPages.appendTrailingSlash = false + for _, notFoundPage := range upstreamNotFoundPages { + optionsForNotFoundPages.TargetPath = "/" + notFoundPage + if optionsForNotFoundPages.Upstream(ctx, giteaRoot, giteaAPIToken, branchTimestampCache, fileResponseCache) { + _ = fileResponseCache.Set(uri+"?timestamp="+strconv.FormatInt(o.BranchTimestamp.Unix(), 10), fileResponse{ + exists: false, + }, fileCacheTimeout) + return true + } + } + } if res != nil { // Update cache if the request is fresh _ = fileResponseCache.Set(uri+"?timestamp="+strconv.FormatInt(o.BranchTimestamp.Unix(), 10), fileResponse{ @@ -166,8 +186,10 @@ func (o *Options) Upstream(ctx *fasthttp.RequestCtx, giteaRoot, giteaAPIToken st } ctx.Response.Header.SetContentType(mimeType) - // Everything's okay so far - ctx.Response.SetStatusCode(fasthttp.StatusOK) + if ( ctx.Response.StatusCode() != fasthttp.StatusNotFound ) { + // Everything's okay so far + ctx.Response.SetStatusCode(fasthttp.StatusOK) + } ctx.Response.Header.SetLastModified(o.BranchTimestamp) log.Debug().Msg("response preparations")