2023-12-31 12:26:56 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"mime"
|
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"code.gitea.io/sdk/gitea"
|
|
|
|
"github.com/patrickmn/go-cache"
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
pageCache = cache.New(6 * time.Hour, 1 * time.Hour)
|
|
|
|
)
|
|
|
|
|
|
|
|
type PageContentCache struct {
|
|
|
|
Content []byte
|
|
|
|
mimeType string
|
|
|
|
}
|
|
|
|
|
|
|
|
func makePageContentCacheEntry(username, path string) string {
|
|
|
|
return username + ":" + path
|
|
|
|
}
|
|
|
|
|
|
|
|
func serveFile(username string, path string, giteaClient *gitea.Client, w http.ResponseWriter) {
|
|
|
|
// Provide a default
|
|
|
|
if path == "" {
|
|
|
|
path = "/index.html"
|
|
|
|
}
|
|
|
|
|
|
|
|
// Strip away a starting / as it messes with Gitea
|
|
|
|
if path[:1] == "/" {
|
|
|
|
path = path[1:]
|
|
|
|
}
|
|
|
|
|
|
|
|
key := makePageContentCacheEntry(username, path)
|
|
|
|
entry, found := pageCache.Get(key)
|
|
|
|
var content []byte
|
|
|
|
var mimeType string
|
2023-12-31 13:08:23 +00:00
|
|
|
var err error
|
2023-12-31 12:26:56 +00:00
|
|
|
if found {
|
|
|
|
log.Debugf("Returning %s from cache", path)
|
|
|
|
content = entry.(PageContentCache).Content
|
|
|
|
mimeType = entry.(PageContentCache).mimeType
|
|
|
|
} else {
|
2023-12-31 13:08:23 +00:00
|
|
|
content, _, err = giteaClient.GetFile(username, "pages", PagesBranch, path, false)
|
2023-12-31 12:26:56 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Errorf("Failed to get file %s (%s)", path, err)
|
|
|
|
w.WriteHeader(404)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
pathParts := strings.Split(path, ".")
|
|
|
|
ext := pathParts[len(pathParts) - 1]
|
2023-12-31 13:08:23 +00:00
|
|
|
mimeType = mime.TypeByExtension("." + ext)
|
2023-12-31 12:26:56 +00:00
|
|
|
|
|
|
|
pageCache.Set(
|
|
|
|
key,
|
|
|
|
PageContentCache{
|
|
|
|
content,
|
|
|
|
mimeType,
|
|
|
|
},
|
|
|
|
cache.DefaultExpiration,
|
|
|
|
)
|
2023-12-31 13:08:23 +00:00
|
|
|
|
|
|
|
log.Debugf("Page %s requested from Gitea and cached in memory", path)
|
2023-12-31 12:26:56 +00:00
|
|
|
}
|
2023-12-31 13:08:23 +00:00
|
|
|
|
2023-12-31 12:26:56 +00:00
|
|
|
w.WriteHeader(200)
|
|
|
|
w.Header().Set("Content-Type", mimeType)
|
|
|
|
w.Write(content)
|
|
|
|
}
|