This commit is contained in:
Ronmi Ren 2025-01-06 10:08:17 +08:00
commit b732e9d7d4
10 changed files with 783 additions and 0 deletions

81
lib/get_file.go Normal file
View file

@ -0,0 +1,81 @@
package lib
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"net/url"
)
type Forgejo struct {
Server url.URL
Token string
Branch string
}
type Info struct {
LastModified string
ETag string
Type string
Size string
}
var ErrNotFound = errors.New("404 not found")
func (f *Forgejo) getFile(ctx context.Context, user, repo, branch, file string) (info Info, content io.Reader, err error) {
u := f.Server
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
}
req.Header.Set("Authorization", "token "+f.Token)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return
}
if resp.StatusCode == http.StatusNotFound {
err = ErrNotFound
return
}
info.LastModified = resp.Header.Get("Last-Modified")
info.ETag = resp.Header.Get("Etag")
info.Type = resp.Header.Get("X-Forgejo-Object-Type")
info.Size = resp.Header.Get("Content-Length")
content = resp.Body
return
}
func (f *Forgejo) GetFile(ctx context.Context, user, repo, branch, file string) (info Info, content io.Reader, err error) {
info, content, err = f.getFile(ctx, user, repo, branch, file)
if err != nil {
return
}
for info.Type == "symlink" {
var data []byte
data, err = io.ReadAll(content)
if err != nil {
return
}
if bytes.HasPrefix(data, []byte("/")) {
err = ErrNotFound
return
}
info, content, err = f.getFile(ctx, user, repo, branch, string(data))
if err != nil {
return
}
}
return
}

58
lib/web.go Normal file
View file

@ -0,0 +1,58 @@
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
}
trySet(w.Header(), "Etag", info.ETag)
trySet(w.Header(), "Last-Modified", info.LastModified)
trySet(w.Header(), "Content-Length", info.Size)
w.WriteHeader(http.StatusOK)
io.Copy(w, content)
}