ตัวอย่างการสร้าง Rest API ด้วย GoLang
บทความนี้เจ้าของบทความจะมายกตัวอย่างการสร้าง Rest API ด้วยภาษา GoLang แบบ NO Database 😊
GO คืออะไร ?
GO หรือ GoLang เป็นภาษาโปรแกรมภาษาฝั่ง Black End และเป็น Open Source ใช้สำหรับการสร้าง API Server หรือ Network Applicatio และสามารถ Build file ให้เป็น Binary ของแต่ล่ะ OS ที่ใช้งาน ทำให้ง่ายต่อการ install program
ทำไมต้อง Golang ?
- Non blocking ไม่ต้องหยุดรอ
- Threads(goroutines) ใช้ stack memory น้อย และสามารถขยาย stack memory วิเคราะห์ตามความจำเป็นโดยอัตโนมัติ
- compiled Machin code ไม่จำเป็นต้องเอา source code ขึ้นไป run บน server
Rest API คืออะไร ?
Soft waere (ที่ใช้ในการยกตัวอย่าง)
อธิบาย Command
//สร้าง Go mudule ได้มาซึ่ง file go.mod เพื่อใช้สารมารถเรียกใช้งาน package อื่นได้
$go mod init goapis.com
go: creating new go.mod: module goapis.com
go: to add module requirements and sums:go mod tidy
//dowload libraries ที่ได้ใช้ และลบ libraries ไม่ได้ใช้ ได้มาซึ่ง file go.sum
$go mod tidy
//run project
$go run main.go
- ตัวอย่างโครงสร้าง Project ทั้งหมด
2. สร้างไฟล์ Model.go
3. สร้างไฟล์ Const.go
4. สร้างไฟล์ StringUtils.go
5. สร้างไฟล์ EmployeeService.go
6. สร้างไฟล์ Handlers.go
7. สร้างไฟล์ Main.go
[Run] $go run main.go
ตัวอย่างการ Test REST API Method GET,POST,PUT,DELETE
สำหรับตัวอย่างการ Test เราจะให้ command curl นะคะ! สำหรับวิธีใช้ command curl เรามาสารถเอา command curl ไปใช้ที่ Terminal ได้เลยค่ะ(สำหรับคนใช้ Linux, UNIX, Aix, macOS)
***ส่วนคนที่ใช้ Windows ก็สามารใช้ Postman เข้ามาช่วยก็ได้ โดยไปที่ Postman >File >Import.. >Raw text >Continue >Import
*** Command curl ที่ใช้งานแต่ล่ะ OS จะแตกต่างกัน
Command curl สำหรับข้อมูล Employee ทั้งหมด
$curl --location --request GET 'http://localhost:9000/api/employee'
Command curl สำหรับข้อมูล Employee ของแต่ล่ะ ID
$curl --location --request GET 'http://localhost:9000/api/employee/1002'
Command curl สำหรับเพิ่มข้อมูล Employee
$curl --location --request POST 'http://localhost:9000/api/employee' \
--header 'Content-Type: application/json' \
--data-raw '{
"FirtsName": "Ammy",
"LastName": "eiei",
"Age": "25",
"Salary": 2000
}'
Command curl สำหรับแก้ไขข้อมูล Employee ของแต่ล่ะ ID
$curl --location --request PUT 'http://localhost:9000/api/employee' \
--header 'Content-Type: application/json' \
--data-raw '{
"Id": "1002",
"FirtsName": "AMMY",
"Age": "22",
"LastName": "eiei",
"Salary": 20000
}'
Command curl สำหรับลบข้อมูล Employee ของแต่ล่ะ ID
$curl --location --request DELETE 'http://localhost:9000/api/employee/1002'
*** NOTE ***
GoLang ไม่เป็น OOP เนื่องจากไม่มี Class และการ Inherit
Source code ทั้งหมด
https://gitlab.com/g796/go-tutorials/goapis