Last active
January 12, 2020 02:15
-
-
Save JustAdam/17c2ebfcb3547bd11930 to your computer and use it in GitHub Desktop.
Go: Handling HUP signal - reloading configuration settings while running
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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