-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
102 lines (86 loc) · 2.33 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
96
97
98
99
100
101
102
package main
import (
"catalog/internal"
"fmt"
"log"
"net"
"os"
"strconv"
"time"
pb "github.com/akolpakov-somehash/headless-ecom-protos/gen/go/catalog"
"github.com/cenkalti/backoff/v4"
"github.com/joho/godotenv"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"google.golang.org/grpc"
)
func loadEnv() error {
// Load environment variables from .env file
err := godotenv.Load()
if err != nil && !os.IsNotExist(err) { //For docker run we don't have the file
return fmt.Errorf("error loading .env file: %v", err)
}
return nil
}
func connectDB() (*gorm.DB, error) {
// Get environment variables
dbUser := os.Getenv("DB_USER")
dbPassword := os.Getenv("DB_PASSWORD")
dbHost := os.Getenv("DB_HOST")
dbPort := os.Getenv("DB_PORT")
dbName := os.Getenv("DB_NAME")
dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", dbUser, dbPassword, dbHost, dbPort, dbName)
var db *gorm.DB
var err error
operation := func() error {
db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
return err
}
exponentialBackOff := backoff.NewExponentialBackOff()
exponentialBackOff.MaxElapsedTime = 2 * time.Minute
exponentialBackOff.MaxInterval = 10 * time.Second
err = backoff.Retry(operation, exponentialBackOff)
if err != nil {
return nil, fmt.Errorf("failed to connect to database: %v", err)
}
return db, nil
}
func startServer(db *gorm.DB, port int) error {
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
if err != nil {
return fmt.Errorf("failed to listen: %v", err)
}
s := grpc.NewServer()
productService := &internal.ProductService{DB: db}
pb.RegisterProductInfoServer(s, &internal.Server{ProductService: productService})
log.Printf("server listening at %v", lis.Addr())
return s.Serve(lis)
}
const (
defaultPort = 50051
)
func main() {
err := loadEnv()
if err != nil {
log.Fatalf("failed to load environment variables: %v", err)
}
db, err := connectDB()
if err != nil {
log.Fatalf("failed to connect to database: %v", err)
}
err = db.AutoMigrate(&internal.DbProduct{})
if err != nil {
log.Fatalf("failed to migrate database: %v", err)
}
port := defaultPort
if p, ok := os.LookupEnv("PORT"); ok {
port, err = strconv.Atoi(p)
if err != nil {
log.Fatalf("invalid port number: %v", err)
}
}
err = startServer(db, port)
if err != nil {
log.Fatalf("failed to start server: %v", err)
}
}