forgejo-pages/lib/web.go
2026-05-15 18:00:59 -03:00

199 lines
4.5 KiB
Go

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
package lib
import (
"context"
"errors"
"fmt"
"io"
"mime"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"strings"
)
type Forgejo struct {
Server url.URL
Token string
Branch string
NotFound string
Files string
}
var ErrNotFound = errors.New("404 not found")
// headers must ot be nil
func (f *Forgejo) GetFile(ctx context.Context, headers map[string]string, user, repo, branch, file string) (ret *http.Response, err error) {
u := f.Server
u.Path = path.Join(
u.Path,
"api/v1/repos",
user,
repo,
"raw",
file,
)
p := u.Query()
p.Set("ref", branch)
u.RawQuery = p.Encode()
fmt.Println(u.String())
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
if err != nil {
return
}
for k, v := range headers {
if v == "" {
continue
}
req.Header.Set(k, v)
}
req.Header.Set("Authorization", "token "+f.Token)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode == http.StatusNotFound {
resp.Body.Close()
return nil, ErrNotFound
}
return resp, nil
}
func UseAPI(bind, wellKnown string, f *Forgejo) (*http.Server, error) {
if f == nil {
return nil, errors.New("forgejo is nil")
}
mux := http.NewServeMux()
if wellKnown != "" {
mux.Handle(
"/.well-known/",
http.StripPrefix(
"/.well-known/",
http.FileServer(http.Dir(wellKnown)),
),
)
}
mux.HandleFunc("/", f.handle)
s := &http.Server{
Addr: bind,
Handler: mux,
}
return s, nil
}
func trySet(h http.Header, key string, src http.Header) {
value := src.Get(key)
if value == "" {
h.Del(key)
return
}
h.Set(key, value)
}
func (f *Forgejo) serveLocalFile(w http.ResponseWriter, r *http.Request, status int) {
path := strings.TrimPrefix(r.URL.Path, "/")
if path == "" {
path = "index.html"
}
if f.Files != "" {
path = filepath.Join(f.Files, path)
}
fmt.Println("Serving local file:", path)
data, err := os.ReadFile(path)
if err != nil {
path := f.NotFound
data, readErr := os.ReadFile(path)
if readErr != nil {
http.Error(w, "404 not found", http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusNotFound)
w.Write(data)
return
}
if ct := mime.TypeByExtension(filepath.Ext(path)); ct != "" {
w.Header().Set("Content-Type", ct)
}
w.WriteHeader(status)
w.Write(data)
}
func (f *Forgejo) handle(w http.ResponseWriter, r *http.Request) {
arr := strings.Split(r.URL.Path[1:], "/")
if len(arr) < 2 {
f.serveLocalFile(w, r, http.StatusOK)
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:], "/")
}
headers := map[string]string{}
headers["If-None-Match"] = r.Header.Get("If-None-Match")
headers["If-Modified-Since"] = r.Header.Get("If-Modified-Since")
headers["If-Range"] = r.Header.Get("If-Range")
headers["Range"] = r.Header.Get("Range")
headers["X-Forwarded-For"] = r.Header.Get("X-Forwarded-For")
headers["X-Forwarded-Host"] = r.Header.Get("X-Forwarded-Host")
headers["X-Forwarded-Proto"] = r.Header.Get("X-Forwarded-Proto")
headers["X-Real-IP"] = r.Header.Get("X-Real-IP")
headers["X-Host"] = r.Header.Get("X-Host")
headers["CF-Connecting-IP"] = r.Header.Get("CF-Connecting-IP")
headers["CF-IPCountry"] = r.Header.Get("CF-IPCountry")
headers["CF-Visitor"] = r.Header.Get("CF-Visitor")
headers["CF-Request-ID"] = r.Header.Get("CF-Request-ID")
headers["CF-Ray"] = r.Header.Get("CF-Ray")
resp, err := f.GetFile(r.Context(), headers, user, repo, f.Branch, file)
if err != nil {
if errors.Is(err, ErrNotFound) {
f.serveLocalFile(w, r, http.StatusNotFound)
return
}
w.WriteHeader(http.StatusNotFound)
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)
}