-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
71 lines (59 loc) · 1.77 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
package main
import (
"log"
"net/http"
"net/http/httputil"
"os"
"github.com/VividCortex/godaemon"
"gopkg.in/alecthomas/kingpin.v2"
)
var (
routedHostnames map[string]int
//Sites contains every routed site
Sites []Site
//HTTPClient is the client used to perform proxied requests
HTTPClient http.Client
)
var (
logFileLoc = kingpin.Flag("log", "Location of the log file").Default("stdout").String()
daemonize = kingpin.Flag("daemon", "If daemonized, the program will run in the background.").Default("true").Bool()
sitesLoc = kingpin.Flag("sites_dir", "Location of site files").Short('h').Default("/etc/hostsplitter/").String()
bindAddr = kingpin.Flag("bind", "Bind address").Short('b').Default(":80").String()
)
func main() {
HTTPClient = http.Client{}
kingpin.Parse()
log.Print("Starting hostsplitter")
if *logFileLoc != "stdout" {
logFile, err := os.OpenFile(*logFileLoc, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0640)
defer logFile.Close()
if err != nil {
log.Fatalf("error opening file: %v", err)
}
log.Print("Using ", *logFileLoc, " for logging")
log.SetOutput(logFile)
}
if *daemonize {
log.Print("Daemonizing... Bye Bye")
godaemon.MakeDaemon(&godaemon.DaemonAttr{})
}
LoadConfig()
log.Fatal(http.ListenAndServe(*bindAddr, &httputil.ReverseProxy{
Director: func(r *http.Request) {
HTTPLog(r)
if i, ok := routedHostnames[string(r.Host)]; ok {
r.Header.Set("X-Hostsplitter-Secret", Sites[i].Secret)
r.Header.Set("Host", r.Host)
r.URL.Scheme = "http"
r.URL.Host = Sites[i].GetBackend()
r.RequestURI = ""
} else {
log.Printf("%q is not routed", r.Host)
}
},
}))
}
//HTTPLog logs an HTTP request
func HTTPLog(r *http.Request) {
log.Printf("httplog> %v %v %v (%q)", r.RemoteAddr, r.Method, r.Host, r.RequestURI)
}