-
Notifications
You must be signed in to change notification settings - Fork 0
/
hrq_worker.go
81 lines (72 loc) · 1.31 KB
/
hrq_worker.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
package hrq
import "log"
type worker struct {
max int
maxQueue int
reqChan chan *reqrsq
hrq *hrq
}
func newWorker2() *worker {
return &worker{}
}
// apply worker options
func (w *worker) apply(opts ...workerOption) {
for _, opt := range opts {
opt(w)
}
}
func newWorker(max int, maxQueue int, hrq *hrq) *worker {
w := &worker{
max: max,
maxQueue: maxQueue,
reqChan: make(chan *reqrsq, maxQueue),
hrq: hrq,
}
w.start()
return w
}
func (w *worker) submitReq(req *reqrsq) {
w.reqChan <- req
}
// start worker
func (w *worker) start() {
for i := 0; i < w.max; i++ {
go w.run()
}
}
func (w *worker) run() {
inner := func() {
// panic recover
defer func() {
if err := recover(); err != nil {
log.Println(err)
}
}()
for {
select {
case reqRsp := <-w.reqChan:
if reqRsp == nil {
continue
}
hrqCxt := reqRsp.req.Context().Value(hrqContextKey)
if hrqCxt == nil {
hrqCxt = reqRsp.req.Context()
}
if w.hrq.checkOverLoad(reqRsp.rsp, reqRsp.req) {
reqRsp.done <- true
continue
}
apt := w.hrq.getAdapter(hrqCxt, reqRsp, w.hrq)
err := apt.Next()
if err != nil {
reqRsp.rsp.WriteHeader(err.Code)
reqRsp.rsp.Write([]byte(err.Message.(string)))
}
reqRsp.done <- true
}
}
}
for {
inner()
}
}