-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathservice.go
71 lines (60 loc) · 1.24 KB
/
service.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
package main
type IpService interface {
Query(ip string) (string, error)
Close()
}
// ------------------------------------------
// ipService
type serviceTask struct {
ip string
result chan *serviceResult
}
type serviceResult struct {
data string
err error
}
type ipService struct {
route QueryRoute
closeQueue chan bool
queue chan *serviceTask
}
func NewIpService(routePath string) (IpService, error) {
route, err := NewQueryRoute(routePath)
if err != nil {
return nil, err
}
is := &ipService{
route: route,
closeQueue: make(chan bool),
queue: make(chan *serviceTask, 1024*10),
}
go is.runQuery()
return is, nil
}
func (is *ipService) Close() {
is.closeQueue <- true
CloseDrivers()
}
func (is *ipService) Query(ip string) (string, error) {
task := &serviceTask{ip: ip, result: make(chan *serviceResult)}
is.queue <- task
r := <-task.result
return r.data, r.err
}
func (is *ipService) runQuery() {
for {
select {
case <-is.closeQueue:
return
case t := <-is.queue:
go func(ip string) {
data, err := is.queryIp(ip)
t.result <- &serviceResult{data, err}
}(t.ip)
}
}
}
func (is *ipService) queryIp(ip string) (string, error) {
drv := is.route.RouteBy(ip)
return drv.Query(ip)
}