/
plugins.go
64 lines (49 loc) · 1.48 KB
/
plugins.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
package storage
import (
"database/sql"
"log"
"os"
"github.com/datagenx/license-generator/internal/generate"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type Storage interface {
Save(data string) error
ReadAll() ([]string, error)
}
func Plugins(sl generate.Slic, data string) error {
// Initialize file
if filePath, isExists := os.LookupEnv("FILE_PATH"); isExists && filePath != "" {
log.Println("file plugin is enabled")
fp := FileStorage{filePath}
return fp.Save(sl, data)
}
// Initialize the mongo
if mongoConnStr, isExists := os.LookupEnv("MONGODB_CONN_STRING"); isExists && mongoConnStr != "" {
log.Println("mongodb plugin is enabled")
getMongoDBClient(mongoConnStr)
}
// Initialize the postgres
if postgresConnStr, isExists := os.LookupEnv("POSTGRES_CONN_STRING"); isExists && postgresConnStr != "" {
log.Println("postgres plugin is enabled")
getPostgresClient(postgresConnStr)
}
return nil
}
func fileInitialize(filePath string) (*os.File, error) {
fh, err := os.OpenFile(filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0640)
defer fh.Close()
return fh, err
}
func getMongoDBClient(mongoConnStr string) (*mongo.Client, error) {
clientOptions := options.Client().ApplyURI(mongoConnStr)
return mongo.NewClient(clientOptions)
}
func getPostgresClient(postgresConnStr string) (*sql.DB, error) {
db, err := sql.Open("postgres", postgresConnStr)
if err != nil {
return nil, err
}
defer db.Close()
return db, nil
}