just forward request and response

This commit is contained in:
Ronmi Ren 2025-01-07 22:13:25 +08:00
commit 6e98e4f5d6
2 changed files with 24 additions and 59 deletions

View file

@ -1,11 +1,9 @@
package lib
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"net/url"
)
@ -16,16 +14,10 @@ type Forgejo struct {
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.ReadCloser, err error) {
// 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 = "/api/v1/repos/" + user + "/" + repo + "/raw/" + file
p := u.Query()
@ -37,6 +29,12 @@ func (f *Forgejo) getFile(ctx context.Context, user, repo, branch, file string)
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 {
@ -47,36 +45,5 @@ func (f *Forgejo) getFile(ctx context.Context, user, repo, branch, file string)
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.ReadCloser, 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
}
content.Close()
if bytes.HasPrefix(data, []byte("/")) {
err = ErrNotFound
return
}
info, content, err = f.getFile(ctx, user, repo, branch, string(data))
if err != nil {
return
}
}
return
return resp, nil
}