glow/github.go
Carlos Alexandro Becker 9ebe39cd09
feat: improve gitlab/github readme url (#456)
* Use GitHub API to find readme filename

* Fix lint errors and typos

* Bring back "tries to find" instead of "finds"

* Rename `readmeURL` to `apiURL`

* Don't close body

* Use GitLab API to find readme filename

* feat: improve gitlab/github readme url

Signed-off-by: Carlos A Becker <caarlos0@users.noreply.github.com>

---------

Signed-off-by: Carlos A Becker <caarlos0@users.noreply.github.com>
Signed-off-by: Carlos Alexandro Becker <caarlos0@users.noreply.github.com>
Co-authored-by: danielwerg <35052399+danielwerg@users.noreply.github.com>
2024-07-09 16:07:39 -03:00

57 lines
1.2 KiB
Go

package main
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
)
// findGitHubREADME tries to find the correct README filename in a repository using GitHub API.
func findGitHubREADME(u *url.URL) (*source, error) {
owner, repo, ok := strings.Cut(strings.TrimPrefix(u.Path, "/"), "/")
if !ok {
return nil, fmt.Errorf("invalid url: %s", u.String())
}
type readme struct {
DownloadURL string `json:"download_url"`
}
apiURL := fmt.Sprintf("https://api.%s/repos/%s/%s/readme", u.Hostname(), owner, repo)
// nolint:bodyclose
// it is closed on the caller
res, err := http.Get(apiURL) // nolint: gosec
if err != nil {
return nil, err
}
body, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}
var result readme
if err := json.Unmarshal(body, &result); err != nil {
return nil, err
}
if res.StatusCode == http.StatusOK {
// nolint:bodyclose
// it is closed on the caller
resp, err := http.Get(result.DownloadURL)
if err != nil {
return nil, err
}
if resp.StatusCode == http.StatusOK {
return &source{resp.Body, result.DownloadURL}, nil
}
}
return nil, errors.New("can't find README in GitHub repository")
}