LatestReleaseUsingAPI retrieves the most recent release version from the GitHub API. It returns the latest version as a string, along with its corresponding URL, or an error in case of request failure or parsing issues with the response. This approach boasts higher reliability compared to LatestRel
(repository string)
| 206 | // LatestReleaseUsingRedirect as it leverages the versioned GitHub API. |
| 207 | // However, it can be affected by GitHub API rate limiting. |
| 208 | func (f releaseFetcher) LatestReleaseUsingAPI(repository string) (tag, url string, err error) { |
| 209 | req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/%s/releases/latest", f.apiEndpoint, repository), nil) |
| 210 | if err != nil { |
| 211 | return "", "", err |
| 212 | } |
| 213 | req.Header.Set("Accept", "application/vnd.github+json") |
| 214 | req.Header.Set("X-GitHub-Api-Version", "2022-11-28") |
| 215 | |
| 216 | res, err := cleanhttp.DefaultClient().Do(req) |
| 217 | if err != nil { |
| 218 | return "", "", fmt.Errorf("GitHub API request failed: %v", err) |
| 219 | } |
| 220 | if res.Body != nil { |
| 221 | defer res.Body.Close() |
| 222 | } |
| 223 | |
| 224 | if res.StatusCode != http.StatusOK { |
| 225 | return "", "", fmt.Errorf("GitHub API request failed with status code: %d", res.StatusCode) |
| 226 | } |
| 227 | |
| 228 | type release struct { |
| 229 | URL string `json:"html_url"` |
| 230 | Tag string `json:"tag_name"` |
| 231 | } |
| 232 | var m release |
| 233 | if err := json.NewDecoder(res.Body).Decode(&m); err != nil { |
| 234 | return "", "", err |
| 235 | } |
| 236 | return m.Tag, m.URL, nil |
| 237 | } |