pages-server/server/upstream/upstream_std.go

149 lines
4.6 KiB
Go
Raw Normal View History

2022-07-27 15:25:08 +00:00
//go:build !fasthttp
package upstream
import (
"errors"
"io"
"net/http"
"strings"
"time"
"github.com/rs/zerolog/log"
"codeberg.org/codeberg/pages/html"
"codeberg.org/codeberg/pages/server/context"
"codeberg.org/codeberg/pages/server/gitea"
)
2022-08-28 13:09:54 +00:00
const (
2022-08-28 14:36:56 +00:00
headerContentType = "Content-Type"
headerETag = "ETag"
headerLastModified = "Last-Modified"
headerIfModifiedSince = "If-Modified-Since"
2022-08-28 13:09:54 +00:00
)
2022-07-27 15:25:08 +00:00
// Upstream requests a file from the Gitea API at GiteaRoot and writes it to the request context.
func (o *Options) Upstream(ctx *context.Context, giteaClient *gitea.Client) (final bool) {
log := log.With().Strs("upstream", []string{o.TargetOwner, o.TargetRepo, o.TargetBranch, o.TargetPath}).Logger()
// Check if the branch exists and when it was modified
if o.BranchTimestamp.IsZero() {
branch := GetBranchTimestamp(giteaClient, o.TargetOwner, o.TargetRepo, o.TargetBranch)
if branch == nil {
2022-08-28 14:21:37 +00:00
html.ReturnErrorPage(ctx, "", http.StatusFailedDependency)
2022-07-27 15:25:08 +00:00
return true
}
o.TargetBranch = branch.Branch
o.BranchTimestamp = branch.Timestamp
}
if o.TargetOwner == "" || o.TargetRepo == "" || o.TargetBranch == "" {
2022-08-28 14:21:37 +00:00
html.ReturnErrorPage(ctx, "", http.StatusBadRequest)
2022-07-27 15:25:08 +00:00
return true
}
// Check if the browser has a cached version
2022-08-28 14:36:56 +00:00
if ifModifiedSince, err := time.Parse(time.RFC1123, string(ctx.Response().Header.Get(headerIfModifiedSince))); err == nil {
2022-07-27 15:25:08 +00:00
if !ifModifiedSince.Before(o.BranchTimestamp) {
ctx.RespWriter.WriteHeader(http.StatusNotModified)
return true
}
}
log.Debug().Msg("preparations")
reader, res, err := giteaClient.ServeRawContent(o.generateUriClientArgs())
log.Debug().Msg("acquisition")
// Handle errors
if (err != nil && errors.Is(err, gitea.ErrorNotFound)) || (res == nil) {
if o.TryIndexPages {
// copy the o struct & try if an index page exists
optionsForIndexPages := *o
optionsForIndexPages.TryIndexPages = false
optionsForIndexPages.appendTrailingSlash = true
for _, indexPage := range upstreamIndexPages {
optionsForIndexPages.TargetPath = strings.TrimSuffix(o.TargetPath, "/") + "/" + indexPage
if optionsForIndexPages.Upstream(ctx, giteaClient) {
return true
}
}
// compatibility fix for GitHub Pages (/example → /example.html)
optionsForIndexPages.appendTrailingSlash = false
2022-08-28 13:33:10 +00:00
optionsForIndexPages.redirectIfExists = strings.TrimSuffix(ctx.Path(), "/") + ".html"
2022-07-27 15:25:08 +00:00
optionsForIndexPages.TargetPath = o.TargetPath + ".html"
if optionsForIndexPages.Upstream(ctx, giteaClient) {
return true
}
}
2022-08-28 13:09:54 +00:00
ctx.Response().StatusCode = http.StatusNotFound
2022-07-27 15:25:08 +00:00
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, giteaClient) {
return true
}
}
}
return false
}
2022-08-28 13:09:54 +00:00
if res != nil && (err != nil || res.StatusCode != http.StatusOK) {
log.Printf("Couldn't fetch contents (status code %d): %v\n", res.StatusCode, err)
2022-08-28 14:21:37 +00:00
html.ReturnErrorPage(ctx, "", http.StatusInternalServerError)
2022-07-27 15:25:08 +00:00
return true
}
// Append trailing slash if missing (for index files), and redirect to fix filenames in general
// o.appendTrailingSlash is only true when looking for index pages
2022-08-28 13:33:10 +00:00
if o.appendTrailingSlash && !strings.HasSuffix(ctx.Path(), "/") {
ctx.Redirect(ctx.Path()+"/", http.StatusTemporaryRedirect)
2022-07-27 15:25:08 +00:00
return true
}
2022-08-28 13:33:10 +00:00
if strings.HasSuffix(ctx.Path(), "/index.html") {
ctx.Redirect(strings.TrimSuffix(ctx.Path(), "index.html"), http.StatusTemporaryRedirect)
2022-07-27 15:25:08 +00:00
return true
}
if o.redirectIfExists != "" {
ctx.Redirect(o.redirectIfExists, http.StatusTemporaryRedirect)
return true
}
log.Debug().Msg("error handling")
// Set the MIME type
mimeType := o.getMimeTypeByExtension()
2022-08-28 13:09:54 +00:00
ctx.Response().Header.Set(headerContentType, mimeType)
2022-07-27 15:25:08 +00:00
// Set ETag
2022-08-28 13:09:54 +00:00
if res != nil {
ctx.Response().Header.Set(headerETag, res.Header.Get(headerETag))
2022-07-27 15:25:08 +00:00
}
2022-08-28 13:09:54 +00:00
if ctx.Response().StatusCode != http.StatusNotFound {
2022-07-27 15:25:08 +00:00
// Everything's okay so far
2022-08-28 13:09:54 +00:00
ctx.Response().StatusCode = http.StatusOK
2022-07-27 15:25:08 +00:00
}
2022-08-28 13:09:54 +00:00
ctx.Response().Header.Set(headerLastModified, o.BranchTimestamp.In(time.UTC).Format(time.RFC1123))
2022-07-27 15:25:08 +00:00
log.Debug().Msg("response preparations")
// Write the response body to the original request
if reader != nil {
_, err := io.Copy(ctx.RespWriter, reader)
if err != nil {
2022-08-28 13:09:54 +00:00
log.Printf("Couldn't write body: %s\n", err)
2022-08-28 14:21:37 +00:00
html.ReturnErrorPage(ctx, "", http.StatusInternalServerError)
2022-07-27 15:25:08 +00:00
return true
}
}
log.Debug().Msg("response")
return true
}