Merge branch 'move-more-logic-into-client' into std-http

This commit is contained in:
6543 2022-07-21 21:58:22 +02:00
commit cfecdb6acc
No known key found for this signature in database
GPG key ID: C99B82E40B027BAE
7 changed files with 40 additions and 42 deletions

View file

@ -10,8 +10,12 @@ import (
"github.com/valyala/fasthttp"
"github.com/valyala/fastjson"
"codeberg.org/codeberg/pages/server/cache"
)
const giteaAPIRepos = "/api/v1/repos/"
type Client struct {
giteaRoot string
giteaAPIToken string
@ -36,24 +40,15 @@ func NewClient(giteaRoot, giteaAPIToken string, fileResponseCache cache.SetGetKe
}
func (client *Client) GiteaRawContent(targetOwner, targetRepo, ref, resource string) ([]byte, error) {
url := joinURL(client.giteaRoot, giteaAPIRepos, targetOwner, targetRepo, "raw", resource+"?ref="+url.QueryEscape(ref))
res, err := client.do(client.contentTimeout, url)
resp, err := client.ServeRawContent(targetOwner, targetRepo, ref, resource)
if err != nil {
return nil, err
}
switch res.StatusCode() {
case fasthttp.StatusOK:
return res.Body(), nil
case fasthttp.StatusNotFound:
return nil, ErrorNotFound
default:
return nil, fmt.Errorf("unexpected status code '%d'", res.StatusCode())
}
return resp.Body(), nil
}
func (client *Client) ServeRawContent(uri string) (*fasthttp.Response, error) {
url := joinURL(client.giteaRoot, giteaAPIRepos, uri)
func (client *Client) ServeRawContent(targetOwner, targetRepo, ref, resource string) (*fasthttp.Response, error) {
url := joinURL(client.giteaRoot, giteaAPIRepos, targetOwner, targetRepo, "raw", resource+"?ref="+url.QueryEscape(ref))
res, err := client.do(client.contentTimeout, url)
if err != nil {
return nil, err
@ -104,3 +99,17 @@ func (client *Client) do(timeout time.Duration, url string) (*fasthttp.Response,
return res, err
}
// TODO: once golang v1.19 is min requirement, we can switch to 'JoinPath()' of 'net/url' package
func joinURL(baseURL string, paths ...string) string {
p := make([]string, 0, len(paths))
for i := range paths {
path := strings.TrimSpace(paths[i])
path = strings.Trim(path, "/")
if len(path) != 0 {
p = append(p, path)
}
}
return baseURL + "/" + strings.Join(p, "/")
}