Infer file mime type
Some checks failed
/ basic (push) Failing after 2m34s

This commit is contained in:
天クマ 2026-05-15 09:58:28 -03:00
commit 857eee205c
2 changed files with 17 additions and 5 deletions

1
.gitignore vendored Normal file
View file

@ -0,0 +1 @@
forgejo-pages

View file

@ -12,6 +12,8 @@ import (
"net/http"
"net/url"
"strings"
"mime"
"path/filepath"
)
type Forgejo struct {
@ -34,7 +36,7 @@ func (f *Forgejo) GetFile(ctx context.Context, headers map[string]string, user,
if err != nil {
return
}
for k, v := range headers {
if v == "" {
continue
@ -50,7 +52,7 @@ func (f *Forgejo) GetFile(ctx context.Context, headers map[string]string, user,
err = ErrNotFound
return
}
return resp, nil
}
@ -102,7 +104,7 @@ func (f *Forgejo) handle(w http.ResponseWriter, r *http.Request) {
}
file = strings.Join(arr[2:], "/")
}
headers := map[string]string{}
headers["If-None-Match"] = r.Header.Get("If-None-Match")
headers["If-Modified-Since"] = r.Header.Get("If-Modified-Since")
@ -124,12 +126,21 @@ func (f *Forgejo) handle(w http.ResponseWriter, r *http.Request) {
return
}
defer resp.Body.Close()
trySet(w.Header(), "Etag", resp.Header)
trySet(w.Header(), "Last-Modified", resp.Header)
trySet(w.Header(), "Content-Length", resp.Header)
trySet(w.Header(), "Content-Range", resp.Header)
contentType := resp.Header.Get("Content-Type")
if contentType == "" || strings.HasPrefix(contentType, "text/plain") {
if ct := mime.TypeByExtension(filepath.Ext(file)); ct != "" {
contentType = ct
}
}
if contentType != "" {
w.Header().Set("Content-Type", contentType)
}
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)
}