Create and manage systemd services from Go.
go get github.com/alirezasn3/go-systemdimport goSystemd "github.com/alirezasn3/go-systemd"
execPath, _ := os.Executable()
// writes /etc/systemd/system/my-app.service, reloads systemd, enables and starts it
err := goSystemd.CreateService(&goSystemd.Service{
Name: "my-app",
ExecStart: execPath,
Restart: "on-failure",
RestartSec: "5s",
})
status, err := goSystemd.StatusService("my-app")
if status.Exists && !status.Active {
err = goSystemd.StartService("my-app")
}
// stops, disables and removes the unit file
err = goSystemd.DeleteService("my-app")| Function | Description |
|---|---|
CreateService(*Service) error |
Write the unit file, daemon-reload, enable, start |
DeleteService(name string) error |
stop, disable, remove the unit file, daemon-reload |
StartService(name string) error |
systemctl start |
StopService(name string) error |
systemctl stop |
StatusService(name string) (*Status, error) |
Unit state; a missing unit is not an error |
DaemonReload() error |
systemctl daemon-reload |
Name and ExecStart are required. Description defaults to Name, WantedBy
defaults to multi-user.target; Restart, RestartSec, After and Wants are
written only when set. The .service suffix on a name is optional everywhere.
Exists, Active, Enabled, LoadState, ActiveState, SubState,
UnitFileState, MainPID, and Raw (the output of systemctl status).
ErrServiceNotFound, ErrPermissionDenied, ErrUnsupportedPlatform — all
comparable with errors.Is.
- Linux only. On darwin and windows every function returns
ErrUnsupportedPlatform, so your code still builds and cross-compiles. - Writing to
/etc/systemd/system/needs root.
MIT