Skip to content

Instantly share code, notes, and snippets.

@phuocglh
Forked from JustAdam/sighup.go
Created August 15, 2019 07:02
Show Gist options
  • Select an option

  • Save phuocglh/fa52f22e9bc4bcdaa6ab7db977ad94ff to your computer and use it in GitHub Desktop.

Select an option

Save phuocglh/fa52f22e9bc4bcdaa6ab7db977ad94ff to your computer and use it in GitHub Desktop.
Go: Handling HUP signal - reloading configuration settings while running
package main
import (
"bufio"
"fmt"
"log"
"os"
"os/signal"
"sync"
"syscall"
"time"
)
type Config struct {
sync.Mutex
files []string
}
func (c *Config) Init() {
c.Lock()
defer c.Unlock()
f, err := os.Open("config")
if err != nil {
log.Fatal(err)
}
c.files = make([]string, 0)
scanner := bufio.NewScanner(f)
for scanner.Scan() {
c.files = append(c.files, scanner.Text())
}
}
func main() {
config := &Config{}
config.Init()
go func() {
sigHUP := make(chan os.Signal, 1)
signal.Notify(sigHUP, syscall.SIGHUP)
for {
select {
case <-sigHUP:
config.Init()
}
}
}()
ticker := time.NewTicker(time.Second * 5)
for {
select {
case <-ticker.C:
//Note: access to config.files here is not concurrent safe (you will get a incomplete copy of it when reading at the same time as an update is happening), but it is used here purely for simplicities sake. It is unlikely your application will need to constantly read the configuration data in like this and will instead use it one time after it has been read in to start your main application..
fmt.Println("Files available:", config.files)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment