refactor: add platform

This commit is contained in:
soulteary 2023-01-09 23:14:52 +08:00
parent 8b887fc35d
commit 2b2997ce49
No known key found for this signature in database
GPG key ID: 8107DBA6BC84D986
5 changed files with 17 additions and 14 deletions

View file

@ -0,0 +1,13 @@
//go:build linux || windows
// +build linux windows
package platform
import (
"errors"
"runtime"
)
func DropPrivileges(uid, gid int) error {
return errors.New("setuid and setgid not supported on " + runtime.GOOS)
}

View file

@ -0,0 +1,22 @@
//go:build !windows && !linux
// +build !windows,!linux
package platform
import (
"syscall"
)
func DropPrivileges(uid, gid int) error {
err := syscall.Setgid(gid)
if err != nil {
return err
}
err = syscall.Setuid(uid)
if err != nil {
return err
}
return nil
}

View file

@ -0,0 +1,55 @@
//go:build !windows
// +build !windows
package platform
import (
"log"
"os"
"os/signal"
"syscall"
"github.com/adnanh/webhook/internal/pidfile"
)
func SetupSignals(signals chan os.Signal, reloadFn func(), pidFile *pidfile.PIDFile) {
log.Printf("setting up os signal watcher\n")
signals = make(chan os.Signal, 1)
signal.Notify(signals, syscall.SIGUSR1)
signal.Notify(signals, syscall.SIGHUP)
signal.Notify(signals, syscall.SIGTERM)
signal.Notify(signals, os.Interrupt)
go watchForSignals(signals, reloadFn, pidFile)
}
func watchForSignals(signals chan os.Signal, reloadFn func(), pidFile *pidfile.PIDFile) {
log.Println("os signal watcher ready")
for {
sig := <-signals
switch sig {
case syscall.SIGUSR1:
log.Println("caught USR1 signal")
reloadFn()
case syscall.SIGHUP:
log.Println("caught HUP signal")
reloadFn()
case os.Interrupt, syscall.SIGTERM:
log.Printf("caught %s signal; exiting\n", sig)
if pidFile != nil {
err := pidFile.Remove()
if err != nil {
log.Print(err)
}
}
os.Exit(0)
default:
log.Printf("caught unhandled signal %+v\n", sig)
}
}
}

View file

@ -0,0 +1,8 @@
//go:build windows
// +build windows
package platform
func SetupSignals() {
// NOOP: Windows doesn't have signals equivalent to the Unix world.
}