-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
94 lines (76 loc) · 2.06 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
package main
import (
"errors"
"firebase.google.com/go"
"github.com/GlidingTracks/gt-backend"
"github.com/GlidingTracks/gt-backend/constant"
"github.com/GlidingTracks/gt-backend/rest"
"golang.org/x/net/context"
"google.golang.org/api/option"
"net/http"
"os"
)
const filename = "main.go"
// main is the first entry-point in application.
func main() {
log := gtbackend.DebugLogPrepareHeader(filename, "main")
app, err := initializeFirebase()
if err != nil {
gtbackend.LogFatalErrNoMsg(log, err)
}
rCors := rest.CompleteRouterSetup(app)
port := os.Getenv("PORT")
if port == "" {
gtbackend.LogFatalNoErrMsg(log, "$PORT must be set")
}
err = http.ListenAndServe(":"+port, rCors)
gtbackend.LogFatalErrNoMsg(log, err)
}
// initializeFirebase gets a App object from Firebase, based on the service account credentials.
func initializeFirebase() (app *firebase.App, err error) {
log := gtbackend.DebugLogPrepareHeader(filename, "initializeFirebase")
if !checkIfFirebaseCredentialsExist() {
if !tryCreateFirebaseCredsFromEnv() {
err = errors.New("could not connect to DB")
return
}
}
config := &firebase.Config{
StorageBucket: constant.FirebaseStorageBucket,
}
opt := option.WithCredentialsFile(constant.GoogleServiceCredName)
app, err = firebase.NewApp(context.Background(), config, opt)
if err != nil {
gtbackend.LogFatalErrMsg(log, err, "error initializing app")
}
return
}
// checkIfFirebaseCredentialsExist will check for credential file, bool
func checkIfFirebaseCredentialsExist() (exist bool) {
exist = false
_, err := os.Open(constant.GoogleServiceCredName)
if err != nil {
return
}
exist = true
return
}
// tryCreateFirebaseCredsFromEnv if cred content is loaded as a environment variable, create cred file from it
func tryCreateFirebaseCredsFromEnv() (success bool) {
success = false
val := os.Getenv(constant.GoogleCredEnvVar)
if val == "" {
return
}
f, err := os.Create(constant.GoogleServiceCredName)
if err != nil {
return
}
defer f.Close()
_, err = f.WriteString(val)
if err != nil {
return
}
success = true
return
}