2021-12-05 17:17:28 +00:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/valyala/fasthttp"
|
|
|
|
|
|
|
|
"codeberg.org/codeberg/pages/html"
|
|
|
|
"codeberg.org/codeberg/pages/server/cache"
|
|
|
|
"codeberg.org/codeberg/pages/server/upstream"
|
|
|
|
)
|
|
|
|
|
|
|
|
// tryUpstream forwards the target request to the Gitea API, and shows an error page on failure.
|
|
|
|
func tryUpstream(ctx *fasthttp.RequestCtx,
|
|
|
|
mainDomainSuffix, trimmedHost []byte,
|
|
|
|
|
|
|
|
targetOptions *upstream.Options,
|
|
|
|
targetOwner, targetRepo, targetBranch, targetPath,
|
|
|
|
|
|
|
|
giteaRoot, giteaAPIToken string,
|
2022-03-27 19:54:06 +00:00
|
|
|
canonicalDomainCache, branchTimestampCache, fileResponseCache cache.SetGetKey,
|
|
|
|
) {
|
2021-12-05 17:17:28 +00:00
|
|
|
// check if a canonical domain exists on a request on MainDomain
|
|
|
|
if bytes.HasSuffix(trimmedHost, mainDomainSuffix) {
|
|
|
|
canonicalDomain, _ := upstream.CheckCanonicalDomain(targetOwner, targetRepo, targetBranch, "", string(mainDomainSuffix), giteaRoot, giteaAPIToken, canonicalDomainCache)
|
|
|
|
if !strings.HasSuffix(strings.SplitN(canonicalDomain, "/", 2)[0], string(mainDomainSuffix)) {
|
|
|
|
canonicalPath := string(ctx.RequestURI())
|
|
|
|
if targetRepo != "pages" {
|
2021-12-09 18:32:30 +00:00
|
|
|
path := strings.SplitN(canonicalPath, "/", 3)
|
|
|
|
if len(path) >= 3 {
|
2021-12-09 19:16:43 +00:00
|
|
|
canonicalPath = "/" + path[2]
|
2021-12-09 18:32:30 +00:00
|
|
|
}
|
2021-12-05 17:17:28 +00:00
|
|
|
}
|
|
|
|
ctx.Redirect("https://"+canonicalDomain+canonicalPath, fasthttp.StatusTemporaryRedirect)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-12-05 18:53:23 +00:00
|
|
|
targetOptions.TargetOwner = targetOwner
|
|
|
|
targetOptions.TargetRepo = targetRepo
|
|
|
|
targetOptions.TargetBranch = targetBranch
|
|
|
|
targetOptions.TargetPath = targetPath
|
|
|
|
|
2021-12-05 17:17:28 +00:00
|
|
|
// Try to request the file from the Gitea API
|
2021-12-05 18:53:23 +00:00
|
|
|
if !targetOptions.Upstream(ctx, giteaRoot, giteaAPIToken, branchTimestampCache, fileResponseCache) {
|
2021-12-05 17:17:28 +00:00
|
|
|
html.ReturnErrorPage(ctx, ctx.Response.StatusCode())
|
|
|
|
}
|
|
|
|
}
|