-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
71 lines (61 loc) · 1.97 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
package main
import (
"context"
"fmt"
log "github.com/sirupsen/logrus"
"github.com/swimresults/start-service/controller"
"github.com/swimresults/start-service/service"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"math/rand"
"os"
"time"
)
var client *mongo.Client
func main() {
ctx := connectDB()
log.SetFormatter(&log.JSONFormatter{
FieldMap: log.FieldMap{
log.FieldKeyTime: "@timestamp",
log.FieldKeyMsg: "message",
},
})
log.SetLevel(log.TraceLevel)
rand.Seed(time.Now().UnixNano())
min := 1000000
max := 9999999
rnd := rand.Intn(max-min) + min
filename := fmt.Sprintf("logs/out-%d.log", rnd)
file, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err == nil {
log.SetOutput(file)
}
defer file.Close()
service.Init(client)
controller.Run()
if err := client.Disconnect(ctx); err != nil {
panic(err)
}
}
func connectDB() context.Context {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
var err error
var uri = "mongodb://"
if os.Getenv("SR_START_MONGO_USERNAME") != "" {
uri += os.Getenv("SR_START_MONGO_USERNAME") + ":" + os.Getenv("SR_START_MONGO_PASSWORD") + "@"
}
uri += os.Getenv("SR_START_MONGO_HOST") + ":" + os.Getenv("SR_START_MONGO_PORT")
client, err = mongo.Connect(ctx, options.Client().ApplyURI(uri))
if err != nil {
fmt.Println("failed when trying to connect to '" + os.Getenv("SR_START_MONGO_HOST") + ":" + os.Getenv("SR_START_MONGO_PORT") + "' as '" + os.Getenv("SR_START_MONGO_USERNAME") + "'")
fmt.Println(fmt.Errorf("unable to connect to mongo database"))
}
err = client.Ping(ctx, readpref.Primary())
if err != nil {
fmt.Println("failed when trying to connect to '" + os.Getenv("SR_START_MONGO_HOST") + ":" + os.Getenv("SR_START_MONGO_PORT") + "' as '" + os.Getenv("SR_START_MONGO_USERNAME") + "'")
fmt.Println(fmt.Errorf("unable to reach mongo database"))
}
return ctx
}