To allow your application to update itself, use selfupdate.DetectLatest to find the newest version from your provider (GitHub, Gitea, or GitLab) and selfupdate.UpdateTo to download and replace the current binary.
Key steps:
- Use
selfupdate.ParseSlug or selfupdate.NewRepositorySlug to define your repository. - Call
selfupdate.DetectLatest(ctx, repository) to get the latest Release information. - Compare the latest version with your current version using
latest.LessOrEqual(currentVersion). - Locate your current executable path using
selfupdate.ExecutablePath(). - Execute the update with
selfupdate.UpdateTo(ctx, latest.AssetURL, latest.AssetName, exePath).
Note: The library handles rollback automatically if the update fails.
func update(version string) error {
// 1. Detect latest release
latest, found, err := selfupdate.DetectLatest(context.Background(), selfupdate.ParseSlug("creativeprojects/resticprofile"))
if err != nil {
return fmt.Errorf("error occurred while detecting version: %w", err)
}
if !found {
return fmt.Errorf("latest version could not be found")
}
// 2. Check if update is needed
if latest.LessOrEqual(version) {
log.Printf("Current version (%s) is the latest", version)
return nil
}
// 3. Get current executable path
exe, err := selfupdate.ExecutablePath()
if err != nil {
return errors.New("could not locate executable path")
}
// 4. Perform the update
if err := selfupdate.UpdateTo(context.Background(), latest.AssetURL, latest.AssetName, exe); err != nil {
return fmt.Errorf("error occurred while updating binary: %w", err)
}
log.Printf("Successfully updated to version %s", latest.Version())
return nil
}