~jzs/aproxy

ref: 18a6f09cae7f280a2a9f506feceaad9e6ef27ef3 aproxy/aproxy.go -rw-r--r-- 3.6 KiB
18a6f09cJens Zeilund Clean up and remove debug code 2 years ago
                                                                                
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
package main

import (
	"crypto/tls"
	"flag"
	"fmt"
	"keybase/sketchground/aproxygo/aproxy"
	"log"
	"net/http"
	"net/http/httputil"
	"net/url"
	"strings"
	"sync"

	"golang.org/x/crypto/acme/autocert"
)

var (
	proxies map[string]*httputil.ReverseProxy
	statics map[string]http.Handler
)

// Config represents a configuration
type Config struct {
	Host   string
	Server string
}

func main() {
	cfgs := []Config{
		Config{
			Host:   "sketchground.dk",
			Server: "http://127.0.0.1:9901",
		},
		Config{
			Host:   "www.sketchground.dk",
			Server: "http://127.0.0.1:9901",
		},
		Config{
			Host:   "blog.sketchground.dk",
			Server: "http://127.0.0.1:9900",
		},
		Config{
			Host:   "pomodoro.sketchground.dk",
			Server: "static:///var/www/pomodoro.sketchground.dk",
		},
		Config{
			Host:   "journal.sketchground.dk",
			Server: "http://127.0.0.1:9900",
		},
		Config{
			Host:   "rutebil.dk",
			Server: "static:///var/www/rutebildk",
		},
		Config{
			Host:   "ikurven.dk",
			Server: "static:///var/www/ikurvendk",
		},
		Config{
			Host:   "www.rutebil.dk",
			Server: "static:///var/www/rutebildk",
		},
		Config{
			Host:   "www.ikurven.dk",
			Server: "static:///var/www/ikurvendk",
		},
	}

	flag.Parse()
	if len(flag.Args()) > 0 {
		cfgs = []Config{}
	}
	for _, a := range flag.Args() {
		arg := strings.Split(a, "=")
		if len(arg) != 2 {
			return
		}
		if arg[0] != "host" {
			continue
		}
		data := strings.Split(arg[1], ";")
		if len(data) != 2 {
			continue
		}
		host := data[0]
		server := data[1]
		cfgs = append(cfgs, Config{Host: host, Server: server})
	}

	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)
	}

	mgr := &autocert.Manager{
		Prompt:     autocert.AcceptTOS,
		HostPolicy: autocert.HostWhitelist(hosts...),
	}

	tracker := aproxy.NewTracker()

	wg := sync.WaitGroup{}
	wg.Add(1)
	go func() {
		log.Println("Starting reverse proxy for ssl connections")
		s := &http.Server{
			Addr:      ":https",
			TLSConfig: &tls.Config{GetCertificate: mgr.GetCertificate},
			Handler:   NewP(true, tracker),
		}
		log.Fatal(s.ListenAndServeTLS("", ""))
		wg.Done()
	}()
	wg.Add(1)
	go func() {
		log.Println("Starting reverse proxy for http connections")
		log.Fatal(http.ListenAndServe(":8080", mgr.HTTPHandler(NewP(false, tracker)))) // port 80
		wg.Done()
	}()
	wg.Wait()

	tracker.Shutdown()
}

func NewP(secure bool, t *aproxy.Tracker) *P {
	p := &P{secure: secure, t: t}

	return p
}

// P struct
type P struct {
	secure bool
	t      *aproxy.Tracker
}

func (p *P) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
	log.Printf("Receiving quest on path: %v", req.URL)
	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
	}

	// TODO: Investigate if this should be guarded for concurrent access?
	p.t.Track(req.Context(), req)

	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
}