DEV Community

Weerasak Chongnguluam
Weerasak Chongnguluam

Posted on • Edited on

9

ลองเล่น Go Fiber web framework

Fiber เป็น Go web framework ที่บอกว่าได้แนวคิดแบบเดียวกันกับ Express framework ของทางฝั่ง Node.js และ ใช้ Fasthttp ซึ่งเป็น library จัดการ HTTP server ที่ไม่ใช่ standard net/http โดยเคลมว่าเป็น HTTP engine ที่เร็วที่สุดสำหรับ Go

เดี๋ยวจะลองเล่นดูสักเล็กน้อยแล้วทำความเข้าใจสไตล์การเขียนของมันดู

เริ่มจากสร้าง module ใหม่สำหรับ program เราก่อนเลย

$ mkdir try-go-fiber && cd try-go-fiber
$ go mod init "try-go-fiber"
Enter fullscreen mode Exit fullscreen mode

ลองง่ายๆสมมติเป็น list posts API สำหรับ list ข้อมูลของ blog post ออกมา เราสามารถสร้าง router เพื่อ map path กับใส่ handler function เพื่อเขียนโค้ดให้ส่ง response กลับออกไปได้แบบนี้

package main

import "github.com/gofiber/fiber/v2"

type PostID int

type Post struct {
    ID    PostID `json:"id"`
    Title string `json:"title"`
    Body  string `json:"body"`
}

var posts = map[PostID]Post{
    1: {
        ID:    1,
        Title: "ลองเล่น Fiber",
        Body:  "Fiber ใช่ง่ายๆเลยสำหรับคนเคยเล่น Express มา",
    },
    2: {
        ID:    2,
        Title: "สิ่งที่อยากทำในปี 2021",
        Body:  "อยากลดน้ำหนักให้น้อยกว่านี้",
    },
}

func main() {
    app := fiber.New()

    app.Get("/posts", func(c *fiber.Ctx) error {
        var result []Post
        for _, post := range posts {
            result = append(result, post)
        }
        return c.JSON(result)
    })

    app.Listen(":3000")
}
Enter fullscreen mode Exit fullscreen mode

จะเห็นว่าวิธีใช้ก็คือเรียก function fiber.New() เพื่อสร้าง app ที่เป็นค่าที่เก็บ context ต่างๆของ application เรา

และเราจะเอามันไปเรียก method ในการกำหนด route ต่างๆเพื่อ map กับ handler จากตัวอย่างเราเรียก app.Get("/posts", ...handler_function...) คือกำหนดถ้าเรียกมาด้วย HTTP GET ที่ path /posts จะทำงานตาม handler function ที่เรากำหนด

ในตัวอย่าง handler function เราเขียนเป็น anonymous function โดยฟังก์ชันต้องรับค่า c *fiber.Ctx กับ return error
ตัว *fiber.Ctx คือค่าที่ Fiber จะส่งมาให้ handler เป็นค่าที่เราใช้ทั้งถึงข้อมูลที่มากับ request และส่งข้อมูล response กับไป

จากตัวอย่างผมเอาข้อมูลของ posts ตอบกลับไปเป็น JSON format ด้วย method c.JSON นั่นเอง

สุดท้ายเราต้องเรียก app.Listen(":3000") เพื่อให้ fiber เปิด HTTP server รอรับ request ที่ port 3000 นั่นเอง

ลองเรียก API endpoint นี้ของเราด้วย curl (แล้ว format ด้วย jq) จะเห็นผลลัพธ์แบบนี้

$ curl -s http://127.0.0.1:3000/posts | jq
[
  {
    "id": 1,
    "title": "ลองเล่น Fiber",
    "body": "Fiber ใช่ง่ายๆเลยสำหรับคนเคยเล่น Express มา"
  },
  {
    "id": 2,
    "title": "สิ่งที่อยากทำในปี 2021",
    "body": "อยากลดน้ำหนักให้น้อยกว่านี้"
  }
]
Enter fullscreen mode Exit fullscreen mode

ซึ่งถ้าเราดูจากสไตล์การเขียน ก็ไม่ยากเท่าไหร่ ถ้าใครเคยใช้ Gin หรือ Echo framework มาก่อนก็แบบไม่ต่างกันเท่าไหร่เลย ที่เหลือก็คงเป็นเรื่องความเร็วที่เคลมว่าเร็วกว่าใครอยากลองเอาไปวัดดูจริงๆกับระบบตัวเองก็ลองย้ายมาเขียนแล้วเทียบกันดูได้เลย

Buy Me A Coffee

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay