-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
95 lines (86 loc) · 1.95 KB
/
main.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
package main
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"log"
"os"
"path"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/gridfs"
"go.mongodb.org/mongo-driver/mongo/options"
)
func InitiateMongoClient() *mongo.Client {
var err error
var client *mongo.Client
uri := "mongodb://localhost:27017"
opts := options.Client()
opts.ApplyURI(uri)
opts.SetMaxPoolSize(5)
if client, err = mongo.Connect(context.Background(), opts); err != nil {
fmt.Println(err.Error())
}
return client
}
func UploadFile(file, filename string) {
data, err := ioutil.ReadFile(file)
if err != nil {
log.Fatal(err)
}
conn := InitiateMongoClient()
bucket, err := gridfs.NewBucket(
conn.Database("myfiles"),
)
if err != nil {
log.Fatal(err)
os.Exit(1)
}
uploadStream, err := bucket.OpenUploadStream(
filename,
)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer uploadStream.Close()
fileSize, err := uploadStream.Write(data)
if err != nil {
log.Fatal(err)
os.Exit(1)
}
log.Printf("Write file to DB was successful. File size: %d\n", fileSize)
}
func Downloadfile(fileName string) {
conn := InitiateMongoClient()
// For CRUD operations, here is an example
db := conn.Database("myfiles")
fsFiles := db.Collection("fs.files")
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
var results bson.M
err := fsFiles.FindOne(ctx, bson.M{}).Decode(&results)
if err != nil {
log.Fatal(err)
}
// you can print out the results
fmt.Println(results)
bucket, _ := gridfs.NewBucket(
db,
)
var buf bytes.Buffer
dStream, err := bucket.DownloadToStreamByName(fileName, &buf)
if err != nil {
log.Fatal(err)
}
fmt.Printf("File size to download: %v\n", dStream)
ioutil.WriteFile(fileName, buf.Bytes(), 0600)
}
func main() {
// Get os.Args values
file := os.Args[1] //os.Args[1] = testfile.zip
filename := path.Base(file)
UploadFile(file, filename)
Downloadfile(filename)
}