~egtann/srp

ref: 88118f3ca0b8930e61ddc56e7b9d20260772ef31 srp/cmd/srp/main.go -rw-r--r-- 1.9 KiB
88118f3c — Evan Tann initial commit 3 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
package main

import (
	"crypto/tls"
	"flag"
	"log"
	"math/rand"
	"net/http"
	"strings"
	"time"

	"github.com/egtann/srp"
	"golang.org/x/crypto/acme/autocert"
)

func main() {
	portTmp := flag.String("p", "3000", "port")
	config := flag.String("c", "config.json", "config file")
	sslURL := flag.String("url", "", "enable ssl on the proxy's url (optional)")
	flag.Parse()

	rand.Seed(time.Now().UnixNano())
	reg, err := srp.NewRegistry(*config)
	if err != nil {
		log.Fatal(err)
	}
	proxy := srp.NewProxy(&Logger{}, reg)

	go func() {
		// Check health at boot and constantly
		client := &http.Client{Timeout: 10 * time.Second}
		err := proxy.CheckHealth(client)
		if err != nil {
			log.Println("failed to check health:", err)
		}
		for range time.Tick(time.Second) {
			err := proxy.CheckHealth(client)
			if err != nil {
				log.Println("failed to check health:", err)
				continue
			}
		}
	}()

	// Start the proxy using SSL if possible
	if len(*sslURL) > 0 {
		hosts := append(reg.Hosts(), *sslURL)
		m := &autocert.Manager{
			Prompt:     autocert.AcceptTOS,
			HostPolicy: autocert.HostWhitelist(hosts...),
		}
		go http.ListenAndServe(":http", m.HTTPHandler(nil))
		s := &http.Server{
			Addr:           ":https",
			Handler:        proxy,
			TLSConfig:      &tls.Config{GetCertificate: m.GetCertificate},
			ReadTimeout:    10 * time.Second,
			WriteTimeout:   10 * time.Second,
			MaxHeaderBytes: 1 << 20,
		}
		log.Println("listening on 443")
		log.Fatal(s.ListenAndServe())
	} else {
		port := strings.TrimLeft(*portTmp, ":")
		log.Println("listening on", port)
		s := &http.Server{
			Addr:           ":" + port,
			Handler:        proxy,
			ReadTimeout:    10 * time.Second,
			WriteTimeout:   10 * time.Second,
			MaxHeaderBytes: 1 << 20,
		}
		log.Fatal(s.ListenAndServe())
	}
}

// Logger implements the srp.Logger interface.
type Logger struct{}

func (l *Logger) Printf(format string, vals ...interface{}) {
	log.Printf(format, vals...)
}