-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaproxy.go
More file actions
95 lines (83 loc) · 2 KB
/
aproxy.go
File metadata and controls
95 lines (83 loc) · 2 KB
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
package main
import (
"fmt"
"log"
"net/http"
"net/http/httputil"
"net/url"
"sync"
"golang.org/x/crypto/acme/autocert"
)
var (
proxies map[string]*httputil.ReverseProxy
statics map[string]http.Handler
)
type Config struct {
Host string
Server string
}
func main() {
cfgs := []Config{
Config{
Host: "blog.sketchground.dk",
Server: "http://127.0.0.1:9900",
},
Config{
Host: "journal.sketchground.dk",
Server: "http://127.0.0.1:9900",
},
Config{
Host: "www.ikurven.dk",
Server: "static:///var/www/ikurvendk",
},
}
hosts := []string{}
// Load services...
proxies = map[string]*httputil.ReverseProxy{}
statics = map[string]http.Handler{}
for _, cfg := range cfgs {
u, _ := url.Parse(cfg.Server)
if u.Scheme == "static" {
log.Printf("Initializing static server for %v -> %v\n", cfg.Host, cfg.Server)
statics[cfg.Host] = http.FileServer(http.Dir(u.Path))
} else {
log.Printf("Initializing proxy connection for %v -> %v\n", cfg.Host, cfg.Server)
proxies[cfg.Host] = httputil.NewSingleHostReverseProxy(u)
}
hosts = append(hosts, cfg.Host)
}
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
log.Println("Starting reverse proxy for ssl connections")
log.Fatal(http.Serve(autocert.NewListener(hosts...), &P{secure: true}))
wg.Done()
}()
wg.Add(1)
go func() {
log.Println("Starting reverse proxy for http connections")
log.Fatal(http.ListenAndServe(":80", &P{})) // port 80
wg.Done()
}()
wg.Wait()
}
type P struct {
secure bool
}
func (p *P) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if !p.secure { // Redirect always if not secure.
u := fmt.Sprintf("https://%v%v", req.Host, req.URL.Path)
http.Redirect(rw, req, u, http.StatusFound)
return
}
if h, ok := proxies[req.Host]; ok { // Check if we have proxies
h.ServeHTTP(rw, req)
return
}
if h, ok := statics[req.Host]; ok { // Check if we have statics
h.ServeHTTP(rw, req)
return
}
fmt.Fprintf(rw, "Nothing here. Go elsewhere.") // Return if no hosts match
return
}