优化本地调试

This commit is contained in:
ExplodingDragon
2025-11-25 20:54:49 +08:00
parent c195f18229
commit 0d49f3387d
2 changed files with 52 additions and 17 deletions

View File

@@ -12,14 +12,16 @@ import (
"path/filepath"
"slices"
"strconv"
"strings"
"time"
"gopkg.d7z.net/gitea-pages/pkg/core"
)
type LocalProvider struct {
graph map[string][]string
path string
graph map[string][]string
path string
overlay map[string][]byte
}
func NewLocalProvider(
@@ -27,11 +29,16 @@ func NewLocalProvider(
path string,
) *LocalProvider {
return &LocalProvider{
graph: graph,
path: path,
graph: graph,
path: path,
overlay: map[string][]byte{},
}
}
func (l *LocalProvider) AddOverlay(path string, overlay []byte) {
l.overlay[strings.Trim(path, "/")] = overlay
}
func (l *LocalProvider) Close() error {
return nil
}
@@ -65,20 +72,28 @@ func (l *LocalProvider) Branches(_ context.Context, owner, repo string) (map[str
}
func (l *LocalProvider) Open(_ context.Context, _, _, _, path string, _ http.Header) (*http.Response, error) {
open, err := os.Open(filepath.Join(l.path, path))
if err != nil {
return nil, errors.Join(err, os.ErrNotExist)
}
defer open.Close()
all, err := io.ReadAll(open)
if err != nil {
return nil, errors.Join(err, os.ErrNotExist)
}
var all []byte
recorder := httptest.NewRecorder()
if data, ok := l.overlay[strings.Trim(path, "/")]; ok {
all = data
recorder.Header().Add("Content-Length", strconv.FormatInt(int64(len(data)), 10))
} else {
open, err := os.Open(filepath.Join(l.path, path))
if err != nil {
return nil, errors.Join(err, os.ErrNotExist)
}
defer open.Close()
all, err = io.ReadAll(open)
if err != nil {
return nil, errors.Join(err, os.ErrNotExist)
}
stat, _ := open.Stat()
recorder.Header().Add("Content-Length", strconv.FormatInt(stat.Size(), 10))
recorder.Header().Add("Last-Modified", stat.ModTime().Format(http.TimeFormat))
}
recorder.Body = bytes.NewBuffer(all)
recorder.Header().Add("Content-Type", mime.TypeByExtension(filepath.Ext(path)))
stat, _ := open.Stat()
recorder.Header().Add("Content-Length", strconv.FormatInt(stat.Size(), 10))
recorder.Header().Add("Last-Modified", stat.ModTime().Format(http.TimeFormat))
return recorder.Result(), nil
}