2021-12-05 17:17:28 +00:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
2022-11-12 19:37:20 +00:00
|
|
|
"net/http"
|
2021-12-05 17:17:28 +00:00
|
|
|
"strings"
|
|
|
|
|
|
|
|
"codeberg.org/codeberg/pages/html"
|
|
|
|
"codeberg.org/codeberg/pages/server/cache"
|
2022-11-12 19:37:20 +00:00
|
|
|
"codeberg.org/codeberg/pages/server/context"
|
2022-06-11 21:02:06 +00:00
|
|
|
"codeberg.org/codeberg/pages/server/gitea"
|
2021-12-05 17:17:28 +00:00
|
|
|
"codeberg.org/codeberg/pages/server/upstream"
|
|
|
|
)
|
|
|
|
|
|
|
|
// tryUpstream forwards the target request to the Gitea API, and shows an error page on failure.
|
2022-11-12 19:37:20 +00:00
|
|
|
func tryUpstream(ctx *context.Context, giteaClient *gitea.Client,
|
|
|
|
mainDomainSuffix, trimmedHost string,
|
2021-12-05 17:17:28 +00:00
|
|
|
|
|
|
|
targetOptions *upstream.Options,
|
2022-06-11 21:02:06 +00:00
|
|
|
targetOwner, targetRepo, targetBranch, targetPath string,
|
2021-12-05 17:17:28 +00:00
|
|
|
|
2022-11-12 19:37:20 +00:00
|
|
|
canonicalDomainCache cache.SetGetKey,
|
2022-03-27 19:54:06 +00:00
|
|
|
) {
|
2021-12-05 17:17:28 +00:00
|
|
|
// check if a canonical domain exists on a request on MainDomain
|
2022-11-12 19:37:20 +00:00
|
|
|
if strings.HasSuffix(trimmedHost, mainDomainSuffix) {
|
2022-06-11 21:02:06 +00:00
|
|
|
canonicalDomain, _ := upstream.CheckCanonicalDomain(giteaClient, targetOwner, targetRepo, targetBranch, "", string(mainDomainSuffix), canonicalDomainCache)
|
2021-12-05 17:17:28 +00:00
|
|
|
if !strings.HasSuffix(strings.SplitN(canonicalDomain, "/", 2)[0], string(mainDomainSuffix)) {
|
2022-11-12 19:37:20 +00:00
|
|
|
canonicalPath := ctx.Req.RequestURI
|
2021-12-05 17:17:28 +00:00
|
|
|
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
|
|
|
}
|
2022-11-12 19:37:20 +00:00
|
|
|
ctx.Redirect("https://"+canonicalDomain+canonicalPath, http.StatusTemporaryRedirect)
|
2021-12-05 17:17:28 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-12-05 18:53:23 +00:00
|
|
|
targetOptions.TargetOwner = targetOwner
|
|
|
|
targetOptions.TargetRepo = targetRepo
|
|
|
|
targetOptions.TargetBranch = targetBranch
|
|
|
|
targetOptions.TargetPath = targetPath
|
2022-08-12 03:06:26 +00:00
|
|
|
targetOptions.Host = string(trimmedHost)
|
2021-12-05 18:53:23 +00:00
|
|
|
|
2021-12-05 17:17:28 +00:00
|
|
|
// Try to request the file from the Gitea API
|
2022-11-12 19:37:20 +00:00
|
|
|
if !targetOptions.Upstream(ctx, giteaClient) {
|
|
|
|
html.ReturnErrorPage(ctx, "", ctx.StatusCode)
|
2021-12-05 17:17:28 +00:00
|
|
|
}
|
|
|
|
}
|