feaT: Allow specifying custom headers in the rio.json

This commit is contained in:
2024-02-03 15:18:37 +01:00
parent 8630855374
commit cf85380ddb
8 changed files with 227 additions and 182 deletions

View File

@@ -9,7 +9,6 @@ import (
"git.polynom.me/rio/internal/constants"
"git.polynom.me/rio/internal/context"
"git.polynom.me/rio/internal/repo"
"github.com/patrickmn/go-cache"
log "github.com/sirupsen/logrus"
@@ -29,7 +28,7 @@ func makePageContentCacheEntry(username, path string) string {
return username + ":" + path
}
func addHeaders(csp, contentType string, contentLength int, w http.ResponseWriter) {
func addHeaders(repoInfo *context.RepositoryInformation, contentType string, contentLength int, w http.ResponseWriter) {
// Always set a content type
if strings.Trim(contentType, " ") == "" {
w.Header().Set("Content-Type", "application/octet-stream")
@@ -41,8 +40,10 @@ func addHeaders(csp, contentType string, contentLength int, w http.ResponseWrite
w.Header().Set("Strict-Transport-Security", "max-age=31536000")
w.Header().Set("Content-Length", strconv.Itoa(contentLength))
if csp != "" {
w.Header().Set("Content-Security-Policy", csp)
if repoInfo != nil {
for key, value := range repoInfo.Headers {
w.Header().Set(key, value)
}
}
}
@@ -74,16 +75,19 @@ func ServeFile(context *context.Context) {
path,
since,
)
csp := repo.GetCSPForRepository(context.Username, context.Reponame, "", context.Global.Gitea)
repoInfo := context.Global.Cache.GetRepositoryInformation(
context.Username,
context.Reponame,
)
if err != nil {
if !found {
log.Errorf("Failed to get file %s/%s/%s (%s)", context.Username, context.Reponame, path, err)
addHeaders(csp, "text/html", 0, context.Writer)
addHeaders(repoInfo, "text/html", 0, context.Writer)
context.Writer.WriteHeader(404)
} else {
log.Debugf("Request failed but page %s is cached in memory", path)
addHeaders(csp, mimeType, len(content), context.Writer)
addHeaders(repoInfo, mimeType, len(content), context.Writer)
context.Writer.WriteHeader(200)
context.Writer.Write(content)
}
@@ -93,7 +97,7 @@ func ServeFile(context *context.Context) {
if found && !changed {
log.Debugf("Page %s is unchanged and cached in memory", path)
addHeaders(csp, mimeType, len(content), context.Writer)
addHeaders(repoInfo, mimeType, len(content), context.Writer)
context.Writer.WriteHeader(200)
context.Writer.Write(content)
return
@@ -115,7 +119,7 @@ func ServeFile(context *context.Context) {
)
log.Debugf("Page %s requested from Gitea and cached in memory at %v", path, now)
addHeaders(csp, mimeType, len(content), context.Writer)
addHeaders(repoInfo, mimeType, len(content), context.Writer)
context.Writer.WriteHeader(200)
context.Writer.Write(content)