hjr265.me / blog /

Go Tidbit: Update Checker with GitHub Releases

After building Printd, Toph’s print daemon, it became necessary to ensure that contest organizers were using the latest version of the software. Since Printd is open-source we host both the code and the release artifacts on GitHub.

The following function uses the Go client library for GitHub to check the latest release and compare the tag with the current version.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package main

import (
	"context"
	"log"
	"time"

	"github.com/google/go-github/v53/github"
	"golang.org/x/mod/semver"
)

var (
	buildTag = "v0.3.0"

	repoOwner = "FurqanSoftware"
	repoName  = "toph-printd"
)

func checkUpdate(ctx context.Context) error {
	// Give your program at most 5 seconds to check for updates.
	ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
	defer cancel()

	// Check the latest release on GitHub.
	client := github.NewClient(nil)
	rel, _, err := client.Repositories.GetLatestRelease(ctx, repoOwner, repoName)
	if err != nil || rel == nil || rel.TagName == nil {
		return err
	}

	// Check if the latest release is newer than the current version.
	if semver.Compare(*rel.TagName, buildTag) > 0 {
		log.Printf("Update available (%s)", *rel.TagName)
	}

	return nil
}

Since the API is accessible publicly you do not need to authenticate the GitHub API requests.

The current version is stored in the buildTag variable. You can easily set this variable at build time using ldflags as shown in Go Tidbit: Setting Variables in Go During Build.


This post is 22nd of my #100DaysToOffload challenge. Want to get involved? Find out more at 100daystooffload.com.


comments powered by Disqus