~jzs/aproxy

ref: 385e0957d78566cdbf2ced486c9253bbcfc0a5ef aproxy/aproxy.go -rw-r--r-- 3.0 KiB
385e0957 — Jens Zeilund Sørensen Made aproxygo configurable only 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
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{}
	flag.Parse()
	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})
	}
	if len(cfgs) == 0 {
		// Return error...
		log.Println("Expected to get configs for a domain, got %v configs", len(cfgs))
		log.Fatal("Usage: aproxygo host=domain;static://... host=domain;http://127.0.0.1:8080...")
	}

	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
}