Skip to main content

ใช้ Fiber

ลองประยุกต์ใช้กับ Fiber CRUD

เราจะลองมาทำ Request อย่างง่ายกันผ่าน Fiber ก่อน (เราจะลงลึกกันหนักๆอีกทีในหัวข้อ GORM)

ลง library คู่กัน

go get github.com/gofiber/fiber/v2
go get github.com/lib/pq

เริ่มต้น setup Database และ fiber

// ประกาศตัวแปร global สำหรับเรียกใช้ database
var db *sql.DB

func SetupDatabase() *sql.DB {
const connectionString = "user=postgres password=yourpassword dbname=yourdbname sslmode=disable"
db, err := sql.Open("postgres", connectionString)
if err != nil {
log.Fatal(err)
}

if err = db.Ping(); err != nil {
log.Fatal(err)
}

return db
}

// ประกาศ struct Product สำหรับการรับ request
type Product struct {
ID int `json:"id"`
Name string `json:"name"`
Price int `json:"price"`
Category string `json:"category"`
}

func main() {
app := fiber.New()
db = SetupDatabase()
defer db.Close()

// ใส่ API ตรงตำแหน่งนี้

app.Listen(":3000")
}

เพิ่ม CRUD function เข้าไป

  • POST /products = CreateProduct
func CreateProduct(c *fiber.Ctx) error {
p := new(Product)
if err := c.BodyParser(p); err != nil {
return err
}

// Insert product into database
_, err := db.Exec("INSERT INTO products (name, price, category) VALUES ($1, $2, $3)", p.Name, p.Price, p.Category)
if err != nil {
return err
}

return c.JSON(p)
}
  • GET /products/:id = GetProduct
func GetProduct(c *fiber.Ctx) error {
id := c.Params("id")
var p Product

// Retrieve product from database
err := db.QueryRow("SELECT id, name, price, category FROM products WHERE id = $1", id).Scan(&p.ID, &p.Name, &p.Price, &p.Category)
if err != nil {
if err == sql.ErrNoRows {
return c.Status(fiber.StatusNotFound).SendString("Product not found")
}
return err
}

return c.JSON(&p)
}
  • PUT /products/:id = UpdateProduct
func UpdateProduct(c *fiber.Ctx) error {
id := c.Params("id")
p := new(Product)
if err := c.BodyParser(p); err != nil {
return err
}

// Update product in the database
_, err := db.Exec("UPDATE products SET name = $1, price = $2, category = $3 WHERE id = $4", p.Name, p.Price, p.Category, id)
if err != nil {
return err
}

p.ID, _ = strconv.Atoi(id)
return c.JSON(p)
}
  • DELETE /products/:id = DeleteProduct
func DeleteProduct(c *fiber.Ctx) error {
id := c.Params("id")

// Delete product from database
_, err := db.Exec("DELETE FROM products WHERE id = $1", id)
if err != nil {
return err
}

return c.SendStatus(fiber.StatusNoContent)
}
  • สุดท้ายเพิ่ม function Handler มาให้ครบ
func main() {
app := fiber.New()
db = SetupDatabase()
defer db.Close()

// Set up routes
app.Post("/products", CreateProduct)
app.Get("/products/:id", GetProduct)
app.Put("/products/:id", UpdateProduct)
app.Delete("/products/:id", DeleteProduct)

app.Listen(":3000")
}

และนี่คือไอเดียในการประยุกต์ใช้ระหว่าง API และ database