-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
66 lines (55 loc) · 1.87 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
package main
// imported package that will use in this file
import (
"log"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/cors"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"github.com/zercle/gofiber-101/book"
"github.com/zercle/gofiber-101/database"
"github.com/zercle/gofiber-101/routers"
)
// function call for init database connection
// param: none
// return: error if occur
func initDatabase() (err error) {
// open connecttion to database and store connection object pointer to database.DBConn and any error to err variable
// https://gorm.io/docs/connecting_to_the_database.html
database.DBConn, err = gorm.Open(sqlite.Open("store.db"), &gorm.Config{})
// if err variable not nil show log message and exit app
if err != nil {
// show log message and exit app
log.Fatal("failed to connect database")
}
// just show log message
log.Println("Connection Opened to Database")
// migrate table into database by model
// https://gorm.io/docs/migration.html
err = database.DBConn.AutoMigrate(&book.Book{})
if err != nil {
log.Fatal("failed to migrate database")
}
log.Println("Database Migrated")
return
}
// go will start here
func main() {
// init Fiber's app with default config
// https://docs.gofiber.io/api/fiber
app := fiber.New()
// basically we'll use fiber's app to handle request and response
// https://docs.gofiber.io/api/app
// all request into this app will handle by CORS middleware before to next handler
// https://docs.gofiber.io/api/middleware
app.Use(cors.New())
// call initDatabase function
initDatabase()
// serve static files from directory `./public` to request / path
// https://docs.gofiber.io/api/app#static
app.Static("/", "./public")
// parse app's pointer
routers.SetupRoutes(app)
// app listen to port 3000/tcp (http://localhost:3000) if error app will exit by log.Fatal
log.Fatal(app.Listen(":3000"))
}