Skip to main content

ใช้งานร่วมกับ Fiber

ประยุกต์ใช้กับ Fiber

go get github.com/gofiber/fiber/v2
package main

import (
"fmt"
"github.com/gofiber/fiber/v2"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"log"
"os"
"time"
)

const (
host = "localhost" // or the Docker service name if running in another container
port = 5432 // default PostgreSQL port
user = "myuser" // as defined in docker-compose.yml
password = "mypassword" // as defined in docker-compose.yml
dbname = "mydatabase" // as defined in docker-compose.yml
)

func main() {
// Configure your PostgreSQL database details here
dsn := fmt.Sprintf("host=%s port=%d user=%s "+
"password=%s dbname=%s sslmode=disable",
host, port, user, password, dbname)

// New logger for detailed SQL logging
newLogger := logger.New(
log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
logger.Config{
SlowThreshold: time.Second, // Slow SQL threshold
LogLevel: logger.Info, // Log level
Colorful: true, // Enable color
},
)

db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{
Logger: newLogger,
})

if err != nil {
panic("failed to connect to database")
}

// Migrate the schema
db.AutoMigrate(&Book{})

// Setup Fiber
app := fiber.New()

// CRUD routes
app.Get("/books", func(c *fiber.Ctx) error {
return getBooks(db, c)
})
app.Get("/books/:id", func(c *fiber.Ctx) error {
return getBook(db, c)
})
app.Post("/books", func(c *fiber.Ctx) error {
return createBook(db, c)
})
app.Put("/books/:id", func(c *fiber.Ctx) error {
return updateBook(db, c)
})
app.Delete("/books/:id", func(c *fiber.Ctx) error {
return deleteBook(db, c)
})

// Start server
log.Fatal(app.Listen(":8000"))
}

อันนี้ก็จะเป็น CRUD ฉบับสมบูรณ์ (ที่สามารถประยุกต์ใช้กับของจริงได้)

Middleware กับ User

Note

  • ทำการเพิ่ม Table User ขึ้นมา ผ่าน Gorm (เก็บ email unique, password แบบ hash)
  • Login แล้วเก็บ JWT Token ไว้

ทำการลง package เพิ่ม

go get golang.org/x/crypto/bcrypt
go get github.com/golang-jwt/jwt/v4
package main

import (
"fmt"
"github.com/gofiber/fiber/v2"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"github.com/golang-jwt/jwt/v4"
"log"
"os"
"time"
)

func authRequired(c *fiber.Ctx) error {
cookie := c.Cookies("jwt")

token, err := jwt.ParseWithClaims(cookie, &jwt.StandardClaims{}, func(token *jwt.Token) (interface{}, error) {
return jwtSecretKey, nil
})

if err != nil || !token.Valid {
return c.SendStatus(fiber.StatusUnauthorized)
}

return c.Next()
}

func main() {
// Code GORM เหมือนเดิม

// add For prevent auth
app.Use("/books", authRequired)

// CRUD routes = API Set book ตัวเดิม

app.Post("/register", func(c *fiber.Ctx) error {
return createUser(db, c)
})

app.Post("/login", func(c *fiber.Ctx) error {
return loginUser(db, c)
})

// Start server
log.Fatal(app.Listen(":8000"))
}