Clavem

Software update checks and downloads in a Go program

GET /v1/releases/<product id>/latest with the key in an X-License-Key header, compare versions with golang.org/x/mod/semver, which needs a leading v, and stream the file with a Range header. Replace the running binary with go-update, which handles Windows.

Clavem stores your builds and answers GET /v1/releases/:productId/latest. A license that is valid for the product gets release notes and files with signed download links. Any other key gets only version and published_at. The release docs list the fields. This page is the Go side: the check, the version comparison, a download that resumes, and replacing the binary. The server behavior it relies on was checked against the live API, and the same logic ran in Rust, Python and C++.

Check

package license

import (
	"context"
	"encoding/json"
	"net/http"
	"net/url"
	"runtime"
	"strconv"
	"time"

	"golang.org/x/mod/semver"
)

type ReleaseFile struct {
	ID       int64  `json:"id"`
	Filename string `json:"filename"`
	Size     int64  `json:"size"`
	Platform string `json:"platform"`
	URL      string `json:"url"` // empty without a valid license
}

type Release struct {
	Version string        `json:"version"`
	Notes   string        `json:"notes"`
	Files   []ReleaseFile `json:"files"`
}

type UpdateState int

const (
	UpToDate UpdateState = iota
	Available
	Locked // newer, but the key is missing or not valid: only the version came back
	Failed
)

// PlatformLabel is the label you chose at upload, for example darwin-arm64, windows-amd64 or linux-amd64.
func PlatformLabel() string { return runtime.GOOS + "-" + runtime.GOARCH }

func (c *Client) CheckForUpdate(ctx context.Context, productID int64, current, licenseKey string) (UpdateState, *Release, error) {
	ctx, cancel := context.WithTimeout(ctx, 8*time.Second)
	defer cancel()
	u := c.Base + "/v1/releases/" + strconv.FormatInt(productID, 10) + "/latest?" + url.Values{"platform": {PlatformLabel()}}.Encode()
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
	if err != nil {
		return Failed, nil, err
	}
	if licenseKey != "" {
		req.Header.Set("X-License-Key", licenseKey) // a header keeps the key out of logs
	}
	res, err := c.HTTP.Do(req)
	if err != nil {
		return Failed, nil, err
	}
	defer res.Body.Close()

	switch res.StatusCode {
	case http.StatusOK:
	case http.StatusNotFound:
		return UpToDate, nil, nil // nothing published yet
	default: // 429 carries Retry-After: 60
		return Failed, nil, &HTTPError{Status: res.StatusCode, RetryAfter: res.Header.Get("Retry-After")}
	}
	var rel Release
	if err := json.NewDecoder(res.Body).Decode(&rel); err != nil {
		return Failed, nil, err
	}
	latest, now := "v"+rel.Version, "v"+current // semver needs the leading v
	if !semver.IsValid(latest) || !semver.IsValid(now) {
		return Failed, nil, &HTTPError{Status: 0, RetryAfter: "version is not semver"}
	}
	if semver.Compare(latest, now) <= 0 {
		return UpToDate, nil, nil
	}
	for _, f := range rel.Files {
		if f.URL != "" {
			return Available, &rel, nil
		}
	}
	return Locked, &rel, nil
}

type HTTPError struct {
	Status     int
	RetryAfter string
}

func (e *HTTPError) Error() string { return "update check failed: HTTP " + strconv.Itoa(e.Status) + " " + e.RetryAfter }

semver.Compare follows Semantic Versioning, so a pre-release sorts below its release. semver requires the v prefix and IsValid is how you detect a bad string, so the code adds the prefix and checks. Locked is the useful middle case: a lapsed customer learns that a newer version exists and can be sent to renew. For the live demo product the check returns UpToDate, because the real API answers 404 with not_found: the demo product has no published release.

The label is the part people get wrong. runtime.GOOS and runtime.GOARCH give darwin-arm64, windows-amd64 or linux-amd64, and the endpoint returns only files whose label equals what you send, plus files with no label. If you uploaded your Mac build with the label macos, a Go program asking for darwin-arm64 sees only the unlabelled files and may report Locked or find no file for its platform. Pick one scheme when you upload and write it down next to your release script. A 429 from this endpoint is counted apart from validation, so an update check never uses up your validation budget.

Download, resume and progress

Request the link when the customer clicks, because it lasts one hour. Use a client with no Timeout, because the field includes reading the body, and bound only the wait for the response header:

import (
	"errors"
	"fmt"
	"io"
	"os"
)

var downloadClient = &http.Client{Transport: &http.Transport{
	Proxy:                 http.ProxyFromEnvironment,
	ResponseHeaderTimeout: 15 * time.Second,
}}

type progressWriter struct {
	w          io.Writer
	have, size int64
	last       int
	OnPercent  func(int)
}

func (p *progressWriter) Write(b []byte) (int, error) {
	n, err := p.w.Write(b)
	p.have += int64(n)
	if pct := int(p.have * 100 / p.size); pct != p.last && p.OnPercent != nil {
		p.last = pct
		p.OnPercent(pct)
	}
	return n, err
}

func Download(ctx context.Context, f ReleaseFile, dest string, onPercent func(int)) error {
	part := dest + ".part"
	var have int64
	if st, err := os.Stat(part); err == nil {
		have = st.Size()
	}
	if have > f.Size {
		_ = os.Remove(part)
		have = 0
	}
	if have < f.Size {
		req, err := http.NewRequestWithContext(ctx, http.MethodGet, f.URL, nil)
		if err != nil {
			return err
		}
		if have > 0 {
			req.Header.Set("Range", fmt.Sprintf("bytes=%d-", have))
		}
		res, err := downloadClient.Do(req)
		if err != nil {
			return err
		}
		defer res.Body.Close()
		flags := os.O_CREATE | os.O_WRONLY
		switch res.StatusCode {
		case http.StatusPartialContent:
			flags |= os.O_APPEND
		case http.StatusOK: // Range ignored: start over
			flags |= os.O_TRUNC
			have = 0
		case http.StatusForbidden:
			return errors.New("the download link expired: check for updates again")
		default:
			return fmt.Errorf("download failed: HTTP %d", res.StatusCode)
		}
		out, err := os.OpenFile(part, flags, 0o644)
		if err != nil {
			return err
		}
		pw := &progressWriter{w: out, have: have, size: f.Size, last: -1, OnPercent: onPercent}
		if _, err := io.Copy(pw, res.Body); err != nil {
			out.Close()
			return err
		}
		if err := out.Close(); err != nil {
			return err
		}
	}
	if st, err := os.Stat(part); err != nil || st.Size() != f.Size {
		return errors.New("size does not match: keep the .part file and resume")
	}
	return os.Rename(part, dest) // replaces an existing file, also on Windows
}

The response has no checksum field, so size is the only integrity check the API gives. Sign the binaries you ship. The context cancels the download when the user quits, and the .part file stays for the next attempt.

Replace the running binary

go-update applies a new executable from any io.Reader, and its README lists Windows support, where a running exe cannot be overwritten in place:

import "github.com/inconshreveable/go-update"

f, err := os.Open(dest)
if err != nil {
	return err
}
defer f.Close()
if err := update.Apply(f, update.Options{}); err != nil {
	if rerr := update.RollbackError(err); rerr != nil {
		return fmt.Errorf("update failed and could not roll back: %w", rerr)
	}
	return err
}
// Ask the user to restart. For a GUI app, download the installer and open it instead.

Its Options has a checksum field. Clavem does not provide one, so leave it empty.

Limits and timing

The releases endpoint allows 120 requests a minute per IP address, counted apart from validation. Check once at start or once a day. “Latest” is the most recently published release, not the highest version number: a backport published after 3.2.1 becomes the answer, so a customer on 3.2.1 sees nothing newer.

Doing this with Clavem

Upload each binary in the dashboard, give it a platform label such as linux-amd64, and publish. The same key that turns the program on fetches the download. Licenses imported from Lemon Squeezy have no order page, so for them this endpoint is how builds are delivered. See the release docs for limits.

Questions

How do I compare versions in Go?

Use golang.org/x/mod/semver. It follows Semantic Versioning 2.0.0 with two exceptions, and it requires a leading v, so 3.2.1 must become v3.2.1 before you call Compare. IsValid tells you whether a string parses.

Can a Go program replace its own executable?

Yes. On Unix a rename over the running file works. On Windows a running executable cannot be overwritten, and the go-update package handles that case. Call update.Apply with the new binary as a reader.

Why does my http.Client time out during a big download?

Client.Timeout includes reading the response body, so a large file hits it while data is still flowing. Leave Timeout unset for downloads and bound the stages you care about, such as the response header, with Transport settings or a context.

Sources

  1. golang.org/x/mod/semver (checked November 2026)
  2. inconshreveable/go-update README (checked November 2026)
  3. Go net/http, Client.Timeout (checked November 2026)