selfupdater

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 2, 2026 License: MIT Imports: 16 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-selfupdater

A small, framework-agnostic self-update library for self-hosted Go applications. It checks GitHub Releases for a newer version, exposes status over HTTP, and — when running on a host with a writable executable — downloads, verifies (SHA-256) and swaps the running binary, then restarts the process.

It works both on bare metal (systemd) and inside containers. Inside a container the binary cannot be replaced in place, so the library only reports that an update is available and the application is expected to respond with a manual update procedure (for example docker compose pull && docker compose up -d).

The library knows nothing about your application. Everything is wired through Config and the optional Hooks.

Features

  • GitHub Releases based, SemVer aware, optional pre-releases.
  • Checksum verification via checksums.txt (SHA-256).
  • Environment detection: inside a container or not; writable executable or not.
  • Drop-in net/http handlers: status, force-check, apply.
  • Background checker on a configurable interval.
  • Restart via exec(2) on Unix (same PID, transparent to systemd) with a Windows fallback.
  • Connection-friendly: Apply swaps the binary and schedules the restart asynchronously, so an HTTP handler can still write its response first.

Requirements

  • Go 1.26+ (follows github.com/creativeprojects/go-selfupdate).
  • Releases must contain an asset for the current GOOS/GOARCH and a checksums.txt file (see the GoReleaser snippet below).

Usage

package main

import (
	"context"
	"log/slog"
	"net/http"
	"os"
	"os/signal"
	"syscall"

	selfupdater "github.com/iAHTOH/go-selfupdater"
)

func main() {
	upd, err := selfupdater.New(selfupdater.Config{
		CurrentVersion: version, // set via -ldflags "-X main.version=1.2.3"
		RepoOwner:      "iAHTOH",
		RepoName:       "my-app",
		AssetPrefix:    "my-app", // assets named my-app_<ver>_<os>_<arch>.tar.gz
		// CheckInterval:   6 * time.Hour, // default
		// AllowPreRelease: false,
		// GitHubToken:     os.Getenv("GITHUB_TOKEN"), // optional: private repos / rate limits
		// HTTPClient:      &http.Client{Timeout: 30 * time.Second}, // optional: proxy, timeouts, tests
		Hooks: selfupdater.Hooks{
			OnUpdateAvailable: func(st selfupdater.Status) {
				slog.Info("update available", "latest", st.LatestVersion)
			},
			BeforeRestart: func() error {
				// Close DB connections, stop workers, flush logs.
				return nil
			},
		},
	})
	if err != nil {
		slog.Error("self-updater init", "error", err)
		os.Exit(1)
	}

	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
	defer stop()
	upd.Start(ctx) // background checks

	mux := http.NewServeMux()
	mux.HandleFunc("GET /api/version", upd.StatusHandler())
	mux.HandleFunc("POST /api/version/check", upd.CheckHandler())
	mux.HandleFunc("POST /api/version/apply", upd.ApplyHandler())

	srv := &http.Server{Addr: ":8080", Handler: mux}
	go func() { _ = srv.ListenAndServe() }()

	<-ctx.Done()
	_ = srv.Shutdown(context.Background())
}
Endpoints
Method Handler Description Responses
GET StatusHandler Cached Status as JSON 200
POST CheckHandler Force a check now, returns the new Status 200, 409 (already in progress), 502 (with error), 405
POST ApplyHandler Download + verify + swap binary, schedule restart 202 restarting, 400 (in container / not writable), 409 no update / already in progress, 405

GET /api/version example:

{
  "current_version": "1.2.2",
  "latest_version": "1.2.3",
  "update_available": true,
  "in_container": false,
  "can_self_update": true,
  "release_url": "https://github.com/iAHTOH/my-app/releases/tag/v1.2.3",
  "release_notes": "## Changes\n- ...",
  "last_checked_at": "2026-12-02T06:00:00Z"
}

GoReleaser

The updater picks the asset matching GOOS/GOARCH. Provide a checksums.txt asset. A minimal .goreleaser.yaml:

version: 2
project_name: my-app

builds:
  - env: [CGO_ENABLED=0]
    goos: [linux, darwin, windows]
    goarch: [amd64, arm64, arm]
    goarm: [7]
    ldflags:
      - -s -w
      - -X main.version={{.Version}}

archives:
  # Names like my-app_1.2.3_linux_amd64.tar.gz so AssetPrefix="my-app" matches.
  - name_template: "{{ .ProjectName }}_{{ .Version }}_{{ .Os }}_{{ .Arch }}{{ with .Arm }}v{{ . }}{{ end }}"
    formats: [tar.gz]
    format_overrides:
      - goos: windows
        formats: [zip]

checksum:
  name_template: "checksums.txt"
  algorithm: sha256

release:
  prerelease: auto

Environment detection

  • In container: /.dockerenv, /run/.containerenv, or IN_CONTAINER=true.
  • Writable executable: POSIX access(2) check on the resolved executable path (symlinks resolved via filepath.EvalSymlinks, so systemd symlinked installs work). Both the executable file and its parent directory must be writable: on Linux a running binary cannot be overwritten directly (ETXTBSY), so the updater writes a temporary file next to it and renames it over the original, which requires a writable directory.
  • CanSelfUpdate is true only when not in a container and the executable is writable.

Security notes

  • Only assets for your own repository are downloaded; checksums.txt (SHA-256) is verified before replacing the binary.
  • Run the service as a dedicated user with write access only to its own binary directory (e.g. /usr/local/bin).
  • In containers, do not enable in-place updates; update by pulling a new image.

License

MIT. See LICENSE.

Documentation

Overview

Package selfupdater provides a portable, framework-agnostic self-update mechanism for self-hosted Go applications. It checks GitHub Releases for a newer version, reports status, and (when running on a host with a writable executable) downloads, verifies and swaps the running binary, then restarts.

The package knows nothing about the host application's business logic. All integration happens through Config and the Hooks interface.

Index

Constants

View Source
const DefaultCheckInterval = 6 * time.Hour

DefaultCheckInterval is used when Config.CheckInterval is zero.

Variables

View Source
var (
	// ErrInContainer is returned by Apply when the process runs inside a
	// container and therefore cannot replace its own binary.
	ErrInContainer = errors.New("self-updater: cannot self-update inside a container")

	// ErrNotWritable is returned by Apply when the executable (or its
	// directory) is not writable by the current user.
	ErrNotWritable = errors.New("self-updater: executable is not writable")

	// ErrNoUpdate is returned by Apply when no update is available.
	ErrNoUpdate = errors.New("self-updater: no update available")

	// ErrUpdateInProgress is returned by Apply (and CheckNow) when another
	// update operation is already running.
	ErrUpdateInProgress = errors.New("self-updater: update already in progress")

	// ErrNotConfigured is returned when a required Config field is missing.
	ErrNotConfigured = errors.New("self-updater: config is incomplete (need CurrentVersion, RepoOwner, RepoName)")
)

Functions

This section is empty.

Types

type Config

type Config struct {
	// CurrentVersion is the version of the running binary (e.g. "1.4.2").
	CurrentVersion string

	// RepoOwner and RepoName identify the GitHub repository to query, e.g.
	// "iAHTOH" and "go-selfupdater".
	RepoOwner string
	RepoName  string

	// AssetPrefix is the prefix of the release asset filename used to locate
	// the correct archive for the current OS/arch, e.g. "eopds" for assets
	// named "eopds_1.4.2_linux_amd64.tar.gz". Optional; when empty the
	// go-selfupdate default naming is used.
	AssetPrefix string

	// CheckInterval is how often the background checker runs. Zero means
	// DefaultCheckInterval.
	CheckInterval time.Duration

	// AllowPreRelease includes pre-releases when looking for the latest
	// version. Disabled by default.
	AllowPreRelease bool

	// GitHubToken is an optional personal access token used to raise the
	// GitHub API rate limit or to access private repositories.
	GitHubToken string

	// HTTPClient is an optional HTTP client used for API calls and downloads.
	// It is mainly useful to configure a proxy or to inject a stub in tests.
	// When nil, http.DefaultClient is used.
	HTTPClient *http.Client

	// Hooks receives update callbacks. Optional.
	Hooks Hooks

	// Logger is the structured logger. When nil, slog.Default() is used.
	Logger *slog.Logger
}

Config configures an Updater. CurrentVersion, RepoOwner and RepoName are required; everything else has sensible defaults.

type Environment

type Environment struct {
	// InContainer is true when the process appears to run inside a container.
	InContainer bool

	// Writable is true when the executable can be replaced in place: both the
	// executable file and its parent directory must be writable.
	Writable bool

	// ExecPath is the resolved absolute path of the running executable.
	ExecPath string
}

Environment describes where the process is running and whether it can replace its own binary.

func Detect

func Detect() (Environment, error)

Detect inspects the current environment.

func (Environment) CanSelfUpdate

func (e Environment) CanSelfUpdate() bool

CanSelfUpdate reports whether an in-place update is possible: we must be on a host (not in a container) and the executable must be replaceable.

type Hooks

type Hooks struct {
	// OnUpdateAvailable is called by the background checker and by CheckNow
	// whenever a newer version than the current one is discovered. It may be
	// called from a background goroutine, so implementations must be
	// concurrency-safe.
	OnUpdateAvailable func(status Status)

	// BeforeRestart is called right before the process is replaced during
	// Apply. It gives the host a chance to close database connections, stop
	// background workers and flush logs. Returning an error aborts the
	// restart (the already-swapped binary stays in place and will be used on
	// the next manual start).
	BeforeRestart func() error
}

Hooks lets the host application observe update events and react before a restart. All fields are optional; nil hooks are ignored.

type Status

type Status struct {
	// CurrentVersion is the version currently running.
	CurrentVersion string `json:"current_version"`

	// LatestVersion is the most recent version found on GitHub. Empty until
	// the first successful check.
	LatestVersion string `json:"latest_version"`

	// UpdateAvailable reports whether LatestVersion is newer than
	// CurrentVersion.
	UpdateAvailable bool `json:"update_available"`

	// InContainer reports whether the process runs inside a container. In a
	// container the binary cannot be replaced in place, so only update
	// notifications are possible.
	InContainer bool `json:"in_container"`

	// CanSelfUpdate reports whether applying an update is possible in this
	// environment (not in a container and the executable is writable).
	CanSelfUpdate bool `json:"can_self_update"`

	// ReleaseURL is a link to the release page on GitHub.
	ReleaseURL string `json:"release_url,omitempty"`

	// ReleaseNotes is the release body (changelog) of the latest release.
	ReleaseNotes string `json:"release_notes,omitempty"`

	// LastCheckedAt is the time of the last check attempt.
	LastCheckedAt time.Time `json:"last_checked_at,omitempty"`

	// LastError is the error message of the most recent failed check, if any.
	LastError string `json:"last_error,omitempty"`
}

Status is a snapshot of the updater state, safe to serialize to JSON and to expose over HTTP.

type Updater

type Updater struct {
	// contains filtered or unexported fields
}

Updater checks for and applies updates. It is safe for concurrent use.

func New

func New(cfg Config) (*Updater, error)

New creates an Updater from cfg, validating required fields and detecting the runtime environment.

func (*Updater) Apply

func (u *Updater) Apply(ctx context.Context) error

Apply downloads, verifies and swaps the running binary with the latest release, then schedules a restart. It returns ErrInContainer or ErrNotWritable when the environment does not allow an in-place update, ErrNoUpdate when there is nothing to apply, and ErrUpdateInProgress when an apply is already running.

Apply returns as soon as the binary has been replaced; the actual restart is performed from a short-lived goroutine after Apply returns, so an HTTP handler can still write its response before the process image is replaced. The BeforeRestart hook runs synchronously before the restart is scheduled; if it returns an error, the restart is aborted and the error is returned.

func (*Updater) ApplyHandler

func (u *Updater) ApplyHandler() http.HandlerFunc

ApplyHandler returns an http.HandlerFunc that downloads and applies the latest update, then schedules a restart. It accepts POST only.

When the environment does not allow an in-place update (running in a container or the executable is not writable), it responds with 400 Bad Request and a JSON reason, so the caller can fall back to a manual update procedure.

func (*Updater) CheckHandler

func (u *Updater) CheckHandler() http.HandlerFunc

CheckHandler returns an http.HandlerFunc that forces an update check now and returns the resulting status. It accepts POST only.

func (*Updater) CheckNow

func (u *Updater) CheckNow(ctx context.Context) (Status, error)

CheckNow performs a synchronous update check and updates the cached status. It returns ErrUpdateInProgress when another check or apply is running.

func (*Updater) Start

func (u *Updater) Start(ctx context.Context)

Start launches the background checker. It checks once shortly after start and then every CheckInterval until ctx is cancelled. It returns immediately.

func (*Updater) Status

func (u *Updater) Status() Status

Status returns the cached status snapshot.

func (*Updater) StatusHandler

func (u *Updater) StatusHandler() http.HandlerFunc

StatusHandler returns an http.HandlerFunc that reports the cached updater status as JSON. The request method is not restricted so it can be used both as a read endpoint and behind routers that only dispatch on path.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址