-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
90 lines (76 loc) · 1.76 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package main
import (
"context"
"fmt"
"github.com/spf13/viper"
"log"
"os"
"os/signal"
"sync/atomic"
"syscall"
"time"
)
type Config struct {
counter atomic.Int64
interval time.Duration
name string
}
func (c *Config) Update() error {
viper.SetConfigName("uv")
viper.SetConfigType("json")
viper.AddConfigPath(".")
viper.AddConfigPath("/etc/uv/")
err := viper.ReadInConfig()
if err != nil {
return err
}
d, err := time.ParseDuration(viper.GetString("interval"))
if err != nil {
return err
}
c.interval = d
c.name = viper.GetString("name")
return nil
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
fmt.Printf("PID: %d\n", os.Getpid())
config := new(Config)
err := config.Update()
if err != nil {
log.Fatal(err)
}
config.counter.Store(0)
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
go func() {
for {
select {
case s := <-signalChan:
switch s {
case syscall.SIGHUP:
log.Println("Reloading Configuration...")
if err := config.Update(); err != nil {
log.Fatal(err)
}
log.Println("Reloaded!")
case syscall.SIGTERM, syscall.SIGINT:
log.Println("Stopping application gracefully...")
cancel() // everyone that consumed this ctx
// let them clean first, they must have handled <-ctx.Done,
// that's why we didn't call os.Exit(code)
}
case <-ctx.Done():
log.Println("Shutting application down...")
// we didn't call cancel() here, because. the cancel() is already called
// by someone else,
// that's why <-ctx.Done() is executed
// ctx.Done() is the product of cancel()
os.Exit(0)
}
}
}()
if err := run(ctx, config, os.Stdout); err != nil {
log.Fatal(err)
}
}