-
Notifications
You must be signed in to change notification settings - Fork 1
/
writer.go
102 lines (75 loc) · 2.02 KB
/
writer.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
package crawler
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type DocsWriter interface {
WriteDocs([]News) (n int, err error)
CheckDuplicate(link string) (err error)
}
/* define printerWriter ( */
type printerWriter struct{}
func (*printerWriter) WriteDocs(docs []News) (n int, err error) {
fmt.Println(docs)
return len(docs), nil
}
func NewPrinterWriter() *printerWriter {
return &printerWriter{}
}
/* ) */
/* define mongodbWriter ( */
type mongoDBWriter struct {
client *mongo.Client
collection *mongo.Collection
}
func (wtr *mongoDBWriter) Init() error {
id := "crowlnews"
pw := "zum123!2#"
addrTemplate := "mongodb+srv://%s:%[email protected]/test?retryWrites=true&w=majority"
mongoDBAddr := fmt.Sprintf(addrTemplate, id, pw)
clientOptions := options.Client().ApplyURI(mongoDBAddr)
client, err := mongo.Connect(context.TODO(), clientOptions)
wtr.client = client
wtr.collection = wtr.client.Database("test").Collection("news")
if err != nil {
return err
}
err = client.Ping(context.TODO(), nil)
if err != nil {
return err
}
fmt.Println("Connected to MongoDB!")
return nil
}
func (wtr *mongoDBWriter) Destroy() error {
err := wtr.client.Disconnect(context.TODO())
if err != nil {
return err
}
fmt.Println("Connection to MongoDB closed.")
return nil
}
func (wtr *mongoDBWriter) CheckDuplicate(link string) (err error) {
url := bson.D{{"url", link}}
var res News
return wtr.collection.FindOne(context.TODO(), url).Decode(&res)
}
func CheckDuplicateURL(collection *mongo.Collection, res *News, filterUrl bson.D) (err error) {
return collection.FindOne(context.TODO(), filterUrl).Decode(res)
}
func (wtr *mongoDBWriter) WriteDocs(docs []News) (n int, err error) {
for _, doc := range docs {
_, err := wtr.collection.InsertOne(context.TODO(), doc)
if err != nil {
return 0, err
}
}
return len(docs), nil
}
func NewMongoDBWriter() *mongoDBWriter {
return &mongoDBWriter{}
}
/* ) */