ทำไมต้องเขียน REST API ด้วย Go?
ภาษา Go ขึ้นชื่อเรื่องความเร็ว ประสิทธิภาพ และความง่ายในการ deploy เป็น binary เดียว ทำให้เหมาะมากกับการเขียน Web API หรือ Backend Service โดยเฉพาะ REST API
เครื่องมือที่ใช้
- ภาษา: Go 1.18+ ขึ้นไป
- Library: net/http (ของ Go เอง)
- Postman หรือ curl: สำหรับทดสอบ API
1. เริ่มต้นโปรเจกต์ใหม่
mkdir go-rest-api cd go-rest-api go mod init github.com/yourname/go-rest-api
2. เขียนไฟล์ main.go
package main import ( "encoding/json" "fmt" "log" "net/http" ) type Item struct { ID string `json:"id"` Name string `json:"name"` } var items = []Item{ {ID: "1", Name: "Example Item"}, } func getItems(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(items) } func main() { http.HandleFunc("/items", getItems) fmt.Println("Server is running on port 8080") log.Fatal(http.ListenAndServe(":8080", nil)) }
3. รัน Server
go run main.go
ผลลัพธ์:
[ { "id": "1", "name": "Example Item" } ]
4. เพิ่ม POST API สำหรับเพิ่มข้อมูล
func createItem(w http.ResponseWriter, r *http.Request) { var newItem Item json.NewDecoder(r.Body).Decode(&newItem) items = append(items, newItem) w.WriteHeader(http.StatusCreated) json.NewEncoder(w).Encode(newItem) }
แล้วปรับ main ดังนี้:
func main() { http.HandleFunc("/items", func(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodGet { getItems(w, r) } else if r.Method == http.MethodPost { createItem(w, r) } }) fmt.Println("Server is running on port 8080") log.Fatal(http.ListenAndServe(":8080", nil)) }
5. ทดสอบ POST ด้วย curl
curl -X POST http://localhost:8080/items \ -H "Content-Type: application/json" \ -d '{"id": "2", "name": "New Item"}'
6. ภาพประกอบ: โครงสร้างการทำงาน REST API ด้วย Go

ข้อดีของ REST API ด้วย Go
- รันเร็วมาก
- Deploy ง่าย แค่ binary
- รองรับ Concurrency ได้ดี
- ไม่มี Dependency ภายนอกเยอะ
ข้อควรระวัง
- ไม่มี middleware เท่ากับ framework เช่น Gin, Fiber (แต่สามารถใช้เสริมได้)
- ต้องจัดการ route เองหาก API เยอะ
อยากต่อยอด?
- ใช้
gorilla/mux
สำหรับจัดการ routing - เพิ่มการเชื่อมต่อกับ PostgreSQL / MySQL
- เพิ่ม JWT หรือ Middleware ตรวจสอบสิทธิ์
- Deploy ด้วย Docker
บทสรุป
หากคุณกำลังมองหาวิธีเขียน REST API อย่างรวดเร็ว ภาษา Go คือหนึ่งในตัวเลือกที่ดีที่สุด เริ่มจาก net/http library ที่มากับภาษาไปจนถึง framework ขั้นสูง Go ช่วยให้คุณ deploy ระบบจริงได้ในเวลาไม่นานเลย!
บทความโดย: poolsawat.com | เขียนโดย: King Pool