forgejo-pages/lib/web.go
2025-01-07 21:41:48 +08:00

69 lines
1.3 KiB
Go

package lib
import (
"errors"
"io"
"net/http"
"strings"
)
func Run(bind string, f *Forgejo) (*http.Server, error) {
if f == nil {
return nil, errors.New("forgejo is nil")
}
s := &http.Server{
Addr: bind,
Handler: http.HandlerFunc(f.handle),
}
return s, nil
}
func trySet(h http.Header, key, value string) {
if value == "" {
h.Del(key)
return
}
h.Set(key, value)
}
func (f *Forgejo) handle(w http.ResponseWriter, r *http.Request) {
arr := strings.Split(r.URL.Path[1:], "/")
if len(arr) < 2 {
w.WriteHeader(http.StatusBadRequest)
return
}
user, repo := arr[0], arr[1]
if user == "u" {
user, repo = repo, f.Branch
}
file := "index.html"
if l := len(arr); l > 2 {
if arr[l-1] == "" {
arr[l-1] = "index.html"
}
file = strings.Join(arr[2:], "/")
}
info, content, err := f.GetFile(r.Context(), user, repo, f.Branch, file)
if err != nil {
w.WriteHeader(http.StatusNotFound)
return
}
defer content.Close()
trySet(w.Header(), "Etag", info.ETag)
trySet(w.Header(), "Last-Modified", info.LastModified)
trySet(w.Header(), "Content-Length", info.Size)
if r.Header.Get("If-None-Match") == info.ETag {
w.WriteHeader(http.StatusNotModified)
return
}
if r.Header.Get("If-Modified-Since") == info.LastModified {
w.WriteHeader(http.StatusNotModified)
return
}
w.WriteHeader(http.StatusOK)
io.Copy(w, content)
}