/
main.go
105 lines (83 loc) · 2.37 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package main
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"github.com/go-redis/redis"
"github.com/machinable/machinable/config"
"github.com/machinable/machinable/dsi/postgres"
"github.com/machinable/machinable/events"
"github.com/machinable/machinable/management"
"github.com/machinable/machinable/projects"
)
// HostSwitch is used to switch routers based on sub domain
type HostSwitch map[string]http.Handler
// Implement the ServeHTTP method on our new type
func (hs HostSwitch) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Check if a http.Handler is registered for the given host.
// If yes, use it to handle the request.
hostParts := strings.Split(r.Host, ".")
// {sub}.{domain}.{tld}
if len(hostParts) < 3 {
http.Error(w, "Project Not Found", 404)
return
}
subDomain := hostParts[0]
handler, ok := hs[subDomain]
if ok {
handler.ServeHTTP(w, r)
} else {
hs["*"].ServeHTTP(w, r)
}
}
func main() {
// load config
configPath := os.Getenv("MACHINABLE_CONFIG_PATH")
file, _ := ioutil.ReadFile(configPath)
config := &config.AppConfig{}
json.Unmarshal([]byte(file), &config)
// secrets come from environment
config.LoadSecrets()
// some values from environment
config.LoadEnv()
// use postgres client
datastore, err := postgres.New(
os.Getenv("POSTGRES_USER"),
os.Getenv("POSTGRES_PW"),
os.Getenv("POSTGRES_HOST"),
os.Getenv("POSTGRES_DB"),
)
if err != nil {
log.Fatal(err)
}
// create a new redis client
cache := redis.NewClient(&redis.Options{
Addr: "cache:6379",
Password: "", // no password set
DB: 0, // use default DB
})
// ping the redis server
pong, err := cache.Ping().Result()
// fail quickly if ping fails
if err != nil {
log.Fatal(pong, err)
}
// create event processor
processor := events.NewProcessor(cache, datastore)
// process web hook results
go func() {
err := processor.ProcessResults()
// fail out
log.Fatal(err)
}()
// switch routers based on subdomain
hostSwitch := make(HostSwitch)
// manage is for the management application api, i.e. project/team management
hostSwitch["manage"] = management.CreateRoutes(datastore, cache, config)
// all other subdomains will be treated as project names, and use the project routes
hostSwitch["*"] = projects.CreateRoutes(datastore, cache, processor, config)
log.Fatal(http.ListenAndServe(":5001", hostSwitch))
}