-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
76 lines (61 loc) · 1.68 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
package caddyconsul
import (
"fmt"
"os"
"syscall"
"time"
"github.com/hashicorp/consul/api"
"github.com/mholt/caddy"
)
var consulClient *api.Client
var kv *api.KV
var catalog *api.Catalog
var caddyfilePath string
var started = time.Now()
func init() {
caddy.RegisterCaddyfileLoader("consulLoader", caddy.LoaderFunc(consulLoader))
}
func reloadCaddy() {
if time.Since(started) < 2*time.Second {
fmt.Println("Not reloading since caddy uptime is too short")
return
}
self, _ := os.FindProcess(os.Getpid())
self.Signal(syscall.SIGUSR1)
}
func consulLoader(serverType string) (caddy.Input, error) {
// return early, if we can
if consulGenerator != nil {
return consulGenerator, nil
}
// Assume localhost, if it's not set in the environment
consulAddress := os.Getenv("CONSUL")
caddyfilePath = os.Getenv("CADDYFILE_PATH")
if consulAddress == "" {
consulAddress = "127.0.0.1:8500"
}
consulConfig := api.DefaultConfig()
consulConfig.Address = consulAddress
var err error
if consulClient == nil {
// setup our consulClient connection
consulClient, err = api.NewClient(consulConfig)
if err != nil {
return nil, err
}
}
// setup our KV connection
kv = consulClient.KV()
// setup our catalog connection
catalog = consulClient.Catalog()
// Actually create the right instance as a generator that caddy needs
consulGenerator = new(caddyfile)
// let the KV and Service portions generate once so we have content for the caddy file when caddy asks the first time
consulGenerator.WatchServices(false)
if len(consulGenerator.Body()) == 0 {
return nil, nil
}
// Start our loop that keeps checking on consul
consulGenerator.StartWatching()
return consulGenerator, nil
}