-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
81 lines (62 loc) · 2.16 KB
/
main.go
File metadata and controls
81 lines (62 loc) · 2.16 KB
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
package main
import (
"fmt"
"log"
"os"
"paymentAPI/handlers"
"paymentAPI/models"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/joho/godotenv"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
func main() {
err := godotenv.Load()
if err != nil {
log.Println("環境変数読み込まれんらしいよ...")
}
// 環境変数から接続情報を取得
dbUser := os.Getenv("POSTGRES_USER")
dbPassword := os.Getenv("POSTGRES_PASSWORD")
dbName := os.Getenv("POSTGRES_DB")
dbHost := os.Getenv("POSTGRES_HOST") // または環境変数から取得
dbPort := "5432" // または環境変数から取得
log.Println("Connecting to database with user:", dbUser, "and db name:", dbName)
dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=disable", dbHost, dbUser, dbPassword, dbName, dbPort)
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatal("エラー出たよだるいね...", err)
}
db.AutoMigrate(&models.Payment{}, &models.Balance{})
var count int64
db.Model(&models.Balance{}).Count(&count)
if count == 0 {
// データが存在しない場合のみ作成
balance := models.Balance{
Balance: 0,
}
db.Create(&balance)
println("データを作成しました")
} else {
println("データは既に存在します")
}
// Ginエンジンのインスタンスを作成
r := gin.Default()
// CORSの設定
r.Use(cors.New(cors.Config{
AllowOrigins: []string{"*"},
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowHeaders: []string{"Origin", "Content-Type", "Content-Length", "Accept-Encoding", "X-CSRF-Token", "Authorization"},
AllowCredentials: true,
}))
r.GET("/", handlers.GetHome(db))
r.GET("/payments", handlers.GetPayments(db))
r.GET("/payments/:id", handlers.GetPayment(db))
r.POST("/payments", handlers.PostPayment(db))
r.PUT("/payments/:id", handlers.PutPayment(db))
r.DELETE("/payments/:id", handlers.DeletePayment(db))
r.GET("/balance", handlers.GetBalance(db))
r.PUT("/balance", handlers.PutBalance(db))
r.Run(":8080")
}