-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.go
89 lines (74 loc) · 1.7 KB
/
server.go
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
package localtunnel
import (
"io"
"net/http"
"strings"
)
var domain string
var secure bool
type createdResp struct {
ID string `json:"id,omitempty"`
URL string `json:"url,omitempty"`
Port int `json:"port,omitempty"`
MaxConn int `json:"max_conn_count,omitempty"`
}
type statusResponse struct {
Tunnels int `json:"tunnels"`
}
type infoResponse struct {
Info string `json:"info"`
}
func handleInfo(w http.ResponseWriter, r *http.Request) {
host := getProto() + domain
info := &infoResponse{Info: "localtunnel server running on " + host}
io.WriteString(w, toJSON(info))
}
func handleNew(w http.ResponseWriter, r *http.Request) {
id := randID()
proxy := NewProxy(id)
proxy.setup()
resp := &createdResp{
ID: id,
URL: getProto() + id + "." + domain,
Port: proxy.port,
MaxConn: 10,
}
go proxy.listen()
io.WriteString(w, toJSON(resp))
}
// SetupServer creates main HTTP server
func SetupServer(port, serverDomain string, isSecure bool) *http.Server {
domain = serverDomain
secure = isSecure
server := &http.Server{
Addr: ":" + port,
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path := r.URL.EscapedPath()
if path == "/api/status" {
resp := &statusResponse{Tunnels: len(proxies)}
io.WriteString(w, toJSON(resp))
} else {
params := r.URL.Query()
if _, ok := params["new"]; ok {
handleNew(w, r)
} else {
hostname := r.Host
id := strings.Split(hostname, ".")[0]
proxy, ok := proxies[id]
if !ok {
handleInfo(w, r)
} else {
proxy.handleRequest(w, r)
}
}
}
}),
}
return server
}
func getProto() string {
if secure {
return "https://"
}
return "http://"
}