aboutsummaryrefslogtreecommitdiff
path: root/server.go
blob: c2c3247ba2f38c322e561a1c5c95d6be01c1b92e (plain)
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
package goxy

import (
	"crypto/tls"
	"fmt"
	"log"
	"net/http"
	"net/http/httputil"
)

type Server struct {
	DataFile string
	Route
	wwwServer http.Server
	tlsServer http.Server
	rpcServer http.Server
}

func NewServer(dataFile, listenWWW, listenTLS, listenRPC string) (*Server, error) {
	r := make(Route)
	server := &Server{
		DataFile: dataFile,
		Route:    r,
		wwwServer: http.Server{
			Addr: listenWWW,
		},
		tlsServer: http.Server{
			Addr: listenTLS,
			TLSConfig: &tls.Config{
				GetCertificate: r.GetCertificate,
			},
		},
		rpcServer: http.Server{
			Addr: listenRPC,
		},
	}
	if dataFile != "" {
		server.Load(dataFile)
	}
	RegisterRPC(server)
	http.Handle("/debug/route", server.Route)
	return server, server.Update()
}

// Update routes from in-memory state
func (s *Server) Update() error {
	wwwMux := http.NewServeMux()
	tlsMux := http.NewServeMux()
	for _, v := range s.Route {
		host := v.ServerName.Host + v.ServerName.Path
		log.Println("Update", host)
		up := v.Upstream
		switch v.ServerName.Scheme {
		case "http", "":
			wwwMux.Handle(host, httputil.NewSingleHostReverseProxy(up))
		case "https":
			wwwMux.Handle(host, http.RedirectHandler("https://"+host, http.StatusMovedPermanently))
			tlsMux.Handle(host, httputil.NewSingleHostReverseProxy(up))
		case "ws":
			wwwMux.Handle(host, http.RedirectHandler("wss://"+host, http.StatusMovedPermanently))
			wwwMux.Handle(host, NewWebSocketProxy(up))
		case "wss":
			tlsMux.Handle(host, NewWebSocketProxy(up))
		}
	}
	wwwMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "%q", r)
	})
	tlsMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "%q", r)
	})
	s.wwwServer.Handler = wwwMux
	s.tlsServer.Handler = tlsMux
	return nil
}

func (s *Server) Start() error {
	errc := make(chan error)
	go func() { errc <- s.wwwServer.ListenAndServe() }()
	go func() { errc <- s.tlsServer.ListenAndServeTLS("", "") }()
	go func() { errc <- s.rpcServer.ListenAndServe() }()
	return <-errc
}