-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathservice.go
111 lines (92 loc) · 1.85 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package main
import (
"context"
"encoding/csv"
"os"
"os/signal"
log "github.com/sirupsen/logrus"
)
const (
onionV2 = 2
onionV3 = 3
)
// Service handler
type Service struct {
cfg *Config
client *Client
csv *csv.Writer
}
// Config data
type Config struct {
TorSocksPort string
Timeout int
Filename string
OnionVersion int
}
// Start the scraping
func (s *Service) Start() error {
var err error
// create our http proxy tor client
s.client, err = NewClient(s.cfg.TorSocksPort, s.cfg.Timeout)
if err != nil {
return err
}
// create our storage layer
s.csv, err = NewStore().CSV(s.cfg.Filename)
if err != nil {
return err
}
// gracefully stop service
c1, cancel := context.WithCancel(context.Background())
exitCh := make(chan struct{})
go func(ctx context.Context) {
for {
s.run(ctx)
select {
case <-ctx.Done():
exitCh <- struct{}{}
return
default:
}
}
}(c1)
// kill signal
signalCh := make(chan os.Signal, 1)
signal.Notify(signalCh, os.Interrupt)
go func() {
select {
case <-signalCh:
log.Info("Kill signal received, please wait to finish task")
cancel()
return
}
}()
<-exitCh
log.Info("Service stopped")
return nil
}
func (s *Service) run(ctx context.Context) {
var onionURL Address
switch s.cfg.OnionVersion {
case onionV2:
onionURL = RandOnionV2()
break
case onionV3:
onionURL = RandOnionV3()
break
default:
onionURL = RandOnionV2()
}
log.Debugf("Scraping %s \n", onionURL.Addr())
defer log.Debugf("Finished scraping %s\n", onionURL.Addr())
resp, err := s.client.Request(onionURL)
if err != nil {
log.Debugf("%s is not available, err: %s", onionURL.Addr(), err.Error())
return
}
err = s.csv.Write([]string{onionURL.Addr(), resp.Title, resp.Description})
if err != nil {
log.Errorf("error writing to file, err: %s \n", err.Error())
}
s.csv.Flush()
}