114 lines
2.5 KiB
Go
114 lines
2.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"
|
|
"net/http"
|
|
"net/url"
|
|
"strings"
|
|
)
|
|
|
|
type Forgejo struct {
|
|
Server url.URL
|
|
Token string
|
|
Branch 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 = "/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
|
|
}
|
|
if resp.StatusCode == http.StatusNotFound {
|
|
err = ErrNotFound
|
|
return
|
|
}
|
|
|
|
return resp, nil
|
|
}
|
|
|
|
func UseAPI(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 string, src http.Header) {
|
|
value := src.Get(key)
|
|
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:], "/")
|
|
}
|
|
|
|
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")
|
|
resp, err := f.GetFile(r.Context(), headers, user, repo, f.Branch, file)
|
|
if err != nil {
|
|
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)
|
|
|
|
w.WriteHeader(resp.StatusCode)
|
|
io.Copy(w, resp.Body)
|
|
}
|