From d9127d1ed9fb0ab4b3a7866f02dee7d8aeafbd5f Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Thu, 2 Jun 2022 15:41:47 +0200 Subject: [PATCH] start using "errors" --- server/gitea/client.go | 25 +++++++++++++++++++++---- server/upstream/upstream.go | 3 ++- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/server/gitea/client.go b/server/gitea/client.go index e936aae..b342b24 100644 --- a/server/gitea/client.go +++ b/server/gitea/client.go @@ -1,6 +1,7 @@ package gitea import ( + "errors" "fmt" "net/url" "path" @@ -13,6 +14,8 @@ import ( const giteaAPIRepos = "/api/v1/repos/" +var ErrorNotFound = errors.New("not found") + type Client struct { giteaRoot string giteaAPIToken string @@ -34,7 +37,6 @@ func NewClient(giteaRoot, giteaAPIToken string) *Client { } // TODOs: -// * own client to store token & giteaRoot // * handle 404 -> page will show 500 atm func (client *Client) GiteaRawContent(targetOwner, targetRepo, ref, resource string) ([]byte, error) { @@ -47,10 +49,14 @@ func (client *Client) GiteaRawContent(targetOwner, targetRepo, ref, resource str if err := getFastHTTPClient(10*time.Second).Do(req, res); err != nil { return nil, err } - if res.StatusCode() != fasthttp.StatusOK { + 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 res.Body(), nil } func (client *Client) ServeRawContent(uri string) (*fasthttp.Response, error) { @@ -63,7 +69,18 @@ func (client *Client) ServeRawContent(uri string) (*fasthttp.Response, error) { resp := fasthttp.AcquireResponse() resp.SetBodyStream(&strings.Reader{}, -1) - return resp, fastClient.Do(req, resp) + if err := fastClient.Do(req, resp); err != nil { + return nil, err + } + + switch resp.StatusCode() { + case fasthttp.StatusOK: + return resp, nil + case fasthttp.StatusNotFound: + return nil, ErrorNotFound + default: + return nil, fmt.Errorf("unexpected status code '%d'", resp.StatusCode()) + } } func (client *Client) GiteaGetRepoBranchTimestamp(repoOwner, repoName, branchName string) (time.Time, error) { diff --git a/server/upstream/upstream.go b/server/upstream/upstream.go index fe91871..edf4f3f 100644 --- a/server/upstream/upstream.go +++ b/server/upstream/upstream.go @@ -2,6 +2,7 @@ package upstream import ( "bytes" + "errors" "fmt" "io" "strings" @@ -79,7 +80,7 @@ func (o *Options) Upstream(ctx *fasthttp.RequestCtx, giteaClient *gitea.Client, log.Debug().Msg("acquisition") // Handle errors - if (res == nil && !cachedResponse.Exists) || (res != nil && res.StatusCode() == fasthttp.StatusNotFound) { + if (err != nil && errors.Is(err, gitea.ErrorNotFound)) || (res == nil && !cachedResponse.Exists) { if o.TryIndexPages { // copy the o struct & try if an index page exists optionsForIndexPages := *o