/
handler.go
87 lines (68 loc) · 1.61 KB
/
handler.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
package procfile
import (
"time"
"fmt"
"net/http"
"github.com/jimrhoskins/soxy/proxy"
"github.com/jimrhoskins/soxy/balancer"
)
var portmanager = NewPortManager(40000, 50000)
type request struct {
W http.ResponseWriter
R *http.Request
done chan bool
}
func req(w http.ResponseWriter, r *http.Request) *request {
return &request{w, r, make(chan bool)}
}
type Handler struct {
Target string
Dir string
p *Procfile
requests chan *request
}
func NewHandler(dir string) *Handler{
handler := &Handler{
Dir: dir,
requests: make(chan *request),
}
go func(){
for {
req := <-handler.requests
handler.p = NewProcfile(handler.Dir, portmanager)
handler.p.SetConcurrency("web=2")
handler.p.LaunchAll()
addrs := handler.p.AddrsFor("web")
if len(addrs) == 0 {
break
}
handlers := make([]http.Handler, 0, len(addrs))
for _, addr := range addrs {
<-Listening(addr)
handlers = append(handlers, proxy.New(addr))
}
loadBalancer := balancer.New(handlers...)
RequestLoop:
for {
go func (req *request){
loadBalancer.ServeHTTP(req.W, req.R)
req.done <- true
}(req)
select {
case req = <-handler.requests:
// Continue Loop
case <-time.After(10 * time.Second):
fmt.Println("Exiting!!!")
handler.p.Kill()
break RequestLoop
}
}
}
}()
return handler
}
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
request := req(w, r)
h.requests <- request
<-request.done
}