Back to Home

วิธีสร้าง REST API ด้วย Golang และ Gin Framework ฉบับรวบรัด

Go Developer17 ธันวาคม 2567Web Development
GoGolangGin FrameworkREST APIBackend

Gin เป็น Web Framework ที่เร็วและมีขนาดเล็กสำหรับ Go

ติดตั้ง

go get -u github.com/gin-gonic/gin

สร้าง API Server

package main import ( "net/http" "github.com/gin-gonic/gin" ) func main() { router := gin.Default() // GET /ping router.GET("/ping", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"message": "pong"}) }) // GET /users router.GET("/users", func(c *gin.Context) { users := []gin.H{{"name": "John"}, {"name": "Jane"}} c.JSON(http.StatusOK, users) }) router.Run(":8080") }

สรุป

Gin ช่วยให้การสร้าง API ด้วย Go เป็นเรื่องง่ายและรวดเร็ว เหมาะสำหรับโปรเจกต์ที่ต้องการ Performance สูง