Go ကို မြန်မာလို
အခြေခံကနေ လေ့လာမယ်
ရိုးရှင်း၊ မြန်၊ concurrency ကောင်းတဲ့ ဘာသာစကားပါ။ Variable နဲ့ Function ကနေ
Struct၊ Interface၊ Goroutine၊ Channel၊ HTTP Server နဲ့ Testing အထိ အခန်း ၁၆ ခန်းနဲ့
ရှင်းပြထားတယ်။ ကုဒ်တိုင်းအတွက် Expected Output ကို ပြထားတာမို့
ကိုယ်ပိုင် terminal မှာ go run နဲ့ တိုက်ကြည့်နိုင်ပါတယ်။
ဘာသာစကား အခြေခံ
Variable · Type · Control · Function · Collection
OOP ပုံစံ + Error
Struct · Pointer · Interface · Error
လက်တွေ့
Goroutine · Module · JSON · HTTP · Test · API
Go ကို browser ထဲမှာ run လို့ မရပါဘူး။ ဒီစာမျက်နှာက ဖတ်ရှုရန် သင်ခန်းစာဖြစ်ပြီး
ကုဒ်တွေရဲ့ အောက်မှာ Expected Output ကို ပြထားတယ်။
go.dev/dl ကနေ Go ကို install ပြီး ကိုယ်ပိုင် terminal မှာ
go run main.go နဲ့ စမ်းပါ။
Go ဆိုတာ ဘာလဲ
Go (Golang) ကို Google က ၂၀၀၉ မှာ ထုတ်ခဲ့တဲ့ ဘာသာစကားပါ။ ရည်ရွယ်ချက်က ရှင်းရှင်း၊ မြန်မြန်၊ လုံခြုံလုံခြုံ ရေးနိုင်ဖို့ပါ။ Python လို ဖတ်ရလွယ်ပြီး C လို မြန်တယ်။ Server၊ CLI tool နဲ့ cloud service တွေမှာ အများကြီး သုံးတယ်။
ဒီခန်း ပြီးရင် သိလာမယ့် အချက်များ
- Go ရဲ့ ထူးခြားချက်နဲ့ ဘယ်နေရာမှာ သုံးလဲ
package mainနဲ့func main()go runနဲ့go buildကွာခြားချက်- Go ကို install ပြီး ပထမဆုံး program run ခြင်း
၁။ သဘောတရား
Go က compiled language ပါ — ကုဒ်ကို machine code အဖြစ် တစ်ခါ ပြောင်းပြီးမှ run တယ်။ ဒါကြောင့် run တဲ့အခါ မြန်တယ်၊ deploy လုပ်တဲ့အခါ ဖိုင် တစ်ခုတည်း (binary) ကို ပို့လိုက်ရုံပါပဲ။ Garbage collector ပါတာမို့ memory ကို ကိုယ်တိုင် လွှတ်ဖို့ မလိုဘူး။
Go မှာ class မရှိပါဘူး။ ဒါပေမယ့် struct နဲ့ interface ကို သုံးပြီး object-ဆန်တဲ့ ပုံစံ ရေးလို့ရတယ် (နောက်ခန်းတွေ)။ Concurrency အတွက် goroutine နဲ့ channel က ဘာသာစကားထဲမှာ တည့်တည့် ပါပြီးသားပါ။
Go က စည်းကမ်း တင်းတင်းကျပ်ကျပ် စက်ရုံပါ။ မသုံးတဲ့ variable ထားရင် compile မဖြစ်ဘူး၊
format မမှန်ရင် gofmt က ချက်ချင်း ပြင်တယ်။ စည်းကမ်း များပေမယ့်
အဖွဲ့သား တိုင်း တူတူ ရေးတာမို့ ကုဒ် ဖတ်ရ လွယ်တယ်။
၂။ Install လုပ်ခြင်း
- go.dev/dl ကနေ OS အတိုင်း installer ယူပါ။
- Terminal ဖွင့်ပြီး
go versionရိုက်ပါ —go version go1.22.xလို ပေါ်ရမယ်။ - Project folder ဆောက်ပြီး
go mod init shopနဲ့ module စပါ။
ကုဒ်ဥပမာ ၁ — Hello, Go
package main
import "fmt"
func main() {
// Go မှာ semicolon မလိုပါ
fmt.Println("မင်္ဂလာပါ, Go!")
fmt.Println("စုစုပေါင်း:", 2+3)
}
မင်္ဂလာပါ, Go! စုစုပေါင်း: 5
package main က ဒါ executable program ဖြစ်ကြောင်း ပြောတယ်။
import "fmt" က format/print package ကို ယူတယ်။
func main() က program စတဲ့ နေရာ — Go က ဒီ function ကို
အလိုအလျောက် ခေါ်တယ်။
၃။ run နဲ့ build
go mod init shop # module အမည် သတ်မှတ်
go run main.go # ချက်ချင်း compile + run
go build # binary ဖိုင် ထုတ် (shop.exe / shop)
./shop # binary ကို run
gofmt -w main.go # format ကို အလိုအလျောက် ပြင်
- Indent အတွက် tab ကို သုံးတယ် —
gofmtက အလိုအလျောက် ညှိပေးတယ်။ - မသုံးတဲ့ import/variable ရှိရင် compile error — ဒါက ကုဒ် သန့်ရှင်းစေတယ်။
- Error ကို
if err != nil { ... }နဲ့ တိုက်ရိုက် ကိုင်တွယ်တာ Go ရဲ့ ပုံစံပါ။
Variable နဲ့ Type — တန်ဖိုး သိမ်းခြင်း
Go က static type ဘာသာစကားပါ — variable တိုင်းမှာ အမျိုးအစား တိကျတယ်၊ ပြောင်းလို့ မရဘူး။ ဒါက bug အများကြီးကို compile အဆင့်မှာတင် ဖမ်းပေးတယ်။
ဒီခန်း ပြီးရင် သိလာမယ့် အချက်များ
varနဲ့:=ကွာခြားချက်- Zero value ဆိုတာ ဘာလဲ
constနဲ့iotafmt.Printfနဲ့ ရလဒ် ပြခြင်း
၁။ ကြေညာခြင်း
package main
import "fmt"
func main() {
var shop string = "NCT Electronics"
var price int = 25000
qty := 2 // type ကို Go က ခန့်မှန်း (int)
total := price * qty
var note string // zero value = ""
var count int // zero value = 0
var ok bool // zero value = false
fmt.Println(shop)
fmt.Println(total)
fmt.Printf("မှတ်ချက်: %q | အရေအတွက်: %d | ok: %v\n", note, count, ok)
// တစ်ကြောင်းတည်း များစွာ
a, b := 10, 20
fmt.Println(a + b)
}
NCT Electronics 50000 မှတ်ချက်: "" | အရေအတွက်: 0 | ok: false 30
:= ကို function ထဲမှာသာ သုံးလို့ရတယ်။ အပြင်မှာ (package level)
var ကို သုံးရတယ်။ := က ဘယ်ဘက်မှာ
variable အသစ် အနည်းဆုံး တစ်ခု ပါရင် ရတယ်။ မသုံးတဲ့ variable ထားရင် compile error ဖြစ်တယ်။
၂။ const နဲ့ iota
const VAT = 0.05
const (
StatusNew = iota // 0
StatusPaid // 1
StatusShipped // 2
StatusDone // 3
)
func main() {
price := 10000.0
fmt.Println("VAT:", price*VAT)
fmt.Println(StatusNew, StatusPaid, StatusShipped, StatusDone)
}
VAT: 500 0 1 2 3
၃။ Printf ရဲ့ Verb များ
| Verb | အသုံး | ဥပမာ ရလဒ် |
|---|---|---|
%v | ပုံမှန် တန်ဖိုး | 25000 |
%d | ကိန်းပြည့် | 42 |
%f | ဒသမ (default 6 လုံး) | 1.500000 |
%.2f | ဒသမ ၂ လုံး | 1.50 |
%s | စာသား | Aung |
%q | ကွက်လပ်ပါ စာသား | "Aung" |
%t | မှန်/မှား | true |
%T | အမျိုးအစား | int |
Go က declared and not used: price လို error ပေးတယ်။
ရေးနေဆဲမှာ ခေတ္တ ပိတ်ထားချင်ရင် _ = price သုံးလို့ ရပေမယ့်
တကယ့် ကုဒ်မှာတော့ ဖျက်တာ ပိုကောင်းတယ်။
Data Type အသေးစိတ်
Go ရဲ့ type တွေက တိကျတယ်။ int နဲ့ int64 က
မတူဘူး၊ အလိုအလျောက် မပြောင်းပေးဘူး။ ဒီခန်းမှာ ဂဏန်း၊ စာသား၊ byte/rune နဲ့
conversion တွေကို ကြည့်မယ်။
ဒီခန်း ပြီးရင် သိလာမယ့် အချက်များ
- ကိန်းအမျိုးအစားများ (int, int64, float64)
- string၊ byte နဲ့ rune
- မြန်မာစာနဲ့ byte အရှည် ကွာခြားချက်
- Type conversion နဲ့
strconv
၁။ ကိန်းနဲ့ စာသား
package main
import (
"fmt"
"strconv"
"unicode/utf8"
)
func main() {
var i int = 42
var f float64 = 1.5
var s string = "မြန်မာ"
var b bool = true
var by byte = 'A' // uint8
var r rune = 'မ' // int32 (unicode code point)
fmt.Printf("%d %f %s %t %c %c\n", i, f, s, b, by, r)
// အလိုအလျောက် မပြောင်းဘူး — တိုက်ရိုက် ပေါင်းလို့ မရ
// fmt.Println(i + f) // ❌ compile error
// ကိုယ်တိုင် ပြောင်းရတယ်
fmt.Println(float64(i) + f)
fmt.Println(i / 5) // 8 (ကိန်းပြည့် စားခြင်း)
fmt.Println(float64(i) / 5) // 8.4
// string → int, int → string
n, err := strconv.Atoi("25000")
fmt.Println(n, err)
fmt.Println(strconv.Itoa(1024))
// စာသား အရှည် — byte နဲ့ rune
fmt.Println(len(s)) // UTF-8 bytes
fmt.Println(utf8.RuneCountInString(s)) // အက္ခရာ အရေအတွက်
}
42 1.500000 မြန်မာ true A မ 43.5 8 8.4 25000 <nil> 1024 18 6
မြန်မာစာလုံး တစ်ခုက UTF-8 မှာ ၃ byte လောက် ရှိတာမို့ len("မြန်မာ") က
18 ဖြစ်ပြီး အက္ခရာ အရေအတွက်က 6 ပါ။ စာသားကို အက္ခရာအလိုက် ခွဲချင်ရင်
[]rune(s) ကို သုံးပါ။
၂။ conversion နဲ့ formatting
price := 25000
qty := 3
total := price * qty
// fmt.Sprintf — စာသား ပြန်ပေးတယ် (print မလုပ်)
label := fmt.Sprintf("%s — %d ခု = %d ကျပ်", "မီးသီး", qty, total)
fmt.Println(label)
// ဒသမ ဖြတ်ခြင်း
rate := 0.075
fmt.Printf("%.1f%%\n", rate*100)
// rune → string
fmt.Println(string(rune(4097))) // မြန်မာ အက္ခရာ
// string → []rune → ပြန်ပေါင်း
chars := []rune("မြန်မာ")
fmt.Println(len(chars))
fmt.Println(string(chars[0]))
မီးသီး — 3 ခု = 75000 ကျပ် 7.5% က 6 မ
- ဂဏန်း ရိုးရိုးအတွက်
int၊ ငွေကြေး/တိကျမှု လိုရင်int64(သို့) decimal package။ - ဒသမအတွက်
float64— ငွေကြေးမှာ float မသုံးတာ ပိုကောင်းတယ် (0.1+0.2 ပြဿနာ)။ - စာသားထဲမှာ ဂဏန်း ထည့်ဖို့
fmt.Sprintfသို့strconv.Itoa။
Control Flow — ဆုံးဖြတ်ခြင်းနဲ့ ထပ်လုပ်ခြင်း
Go မှာ loop က for တစ်မျိုးတည်း ရှိတယ် — while မရှိဘူး။
ဒါပေမယ့် for ကို ပုံစံ သုံးမျိုး ရေးလို့ရတာမို့ လုံလောက်တယ်။ if နဲ့ switch ကလည်း
ရိုးရှင်းပြီး အန္တရာယ် နည်းအောင် ဒီဇိုင်းထုတ်ထားတယ်။
ဒီခန်း ပြီးရင် သိလာမယ့် အချက်များ
- if ထဲမှာ init statement ရေးခြင်း
- switch ရဲ့ အထူးအချက်များ
- for ရဲ့ ပုံစံ သုံးမျိုး
- range နဲ့ slice/map ကို လှည့်ခြင်း
၁။ if / switch
package main
import "fmt"
func main() {
total := 45000
// ကွင်း မလိုပါ
if total >= 50000 {
fmt.Println("လျှော့စျေး 10%")
} else if total >= 30000 {
fmt.Println("လျှော့စျေး 5%")
} else {
fmt.Println("လျှော့စျေး မရ")
}
// if ထဲမှာ variable ကြေညာလို့ရ (ဒီ if အတွင်းသာ ရှိ)
if vat := total * 5 / 100; vat > 2000 {
fmt.Println("VAT:", vat)
}
// switch — break က အလိုအလျောက် ပါပြီး
day := "Sat"
switch day {
case "Sat", "Sun":
fmt.Println("အားလပ်ရက်")
case "Mon", "Tue", "Wed", "Thu", "Fri":
fmt.Println("အလုပ်ရက်")
default:
fmt.Println("မသိတဲ့ ရက်")
}
// condition မပါတဲ့ switch — if/else ရှည် တွေအတွက်
score := 82
switch {
case score >= 90:
fmt.Println("A")
case score >= 80:
fmt.Println("B")
default:
fmt.Println("C")
}
}
လျှော့စျေး 5% VAT: 2250 အားလပ်ရက် B
Go ရဲ့ switch မှာ break က အလိုအလျောက် ပါတယ် — case တစ်ခု
ပြီးရင် ရပ်တယ်။ အောက်ကို ဆက်ချင်ရင် fallthrough ကို
တမင် ရေးရတယ်။ ဒါက အမှား နည်းစေတယ်။
၂။ for ရဲ့ ပုံစံ သုံးမျိုး
// ၁။ ပုံမှန် for
for i := 1; i <= 3; i++ {
fmt.Println("ပတ်", i)
}
// ၂။ while ပုံစံ
n := 0
for n < 3 {
fmt.Println("n =", n)
n++
}
// ၃။ အဆုံးမရှိ loop (break နဲ့ ရပ်)
count := 0
for {
count++
if count == 2 {
break
}
}
// range — index, value
prices := []int{25000, 12000, 8000}
for i, p := range prices {
fmt.Println(i, p)
}
// index မလိုရင် _
for _, p := range prices {
fmt.Println("ဈေး:", p)
}
ပတ် 1 ပတ် 2 ပတ် 3 n = 0 n = 1 n = 2 0 25000 1 12000 2 8000 ဈေး: 25000 ဈေး: 12000 ဈေး: 8000
Loop နှစ်ခု ထပ်ထားရင် အပြင်ကို ရပ်ချင်တဲ့အခါ label ကို သုံးတယ်။
outer: ကို for အပေါ်မှာ ရေးပြီး break outer
လို့ ခေါ်တယ်။ ဒါက ကုဒ် ဖတ်ရ လွယ်စေတယ်။
Function — တစ်ခုထက် ပိုပြန်ပေးနိုင်တယ်
Go function က တန်ဖိုး တစ်ခုတည်း မဟုတ်ဘဲ နှစ်ခု၊ သုံးခု ပြန်ပေးလို့ ရတယ်။
ဒါက error ကို ရလဒ်နဲ့အတူ ပြန်ပေးတဲ့ Go ရဲ့ အဓိက ပုံစံ ဖြစ်လာတယ်။
defer ကလည်း ဖိုင်/connection ပိတ်တာကို သေချာစေတယ်။
ဒီခန်း ပြီးရင် သိလာမယ့် အချက်များ
- Multiple return values
- Variadic parameter (
...int) - Function ကို တန်ဖိုးအဖြစ် သုံးခြင်း
deferရဲ့ အလုပ်လုပ်ပုံ
ကုဒ်ဥပမာ ၁ — Multiple Return
package main
import (
"errors"
"fmt"
)
// (int, error) — ရလဒ်နဲ့ error ကို အတူ ပြန်
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("သုညနဲ့ စားလို့ မရပါ")
}
return a / b, nil
}
// variadic — ကိန်း မည်မျှပါ လက်ခံ
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
// function ကို parameter အဖြစ်
func apply(nums []int, fn func(int) int) []int {
out := make([]int, 0, len(nums))
for _, n := range nums {
out = append(out, fn(n))
}
return out
}
func main() {
result, err := divide(10, 0)
fmt.Println(result, err)
ok, _ := divide(10, 4)
fmt.Println(ok)
fmt.Println(sum(1, 2, 3, 4))
doubled := apply([]int{1, 2, 3}, func(n int) int { return n * 2 })
fmt.Println(doubled)
// defer — function မဆုံးခင် နောက်ဆုံး run တယ် (LIFO)
defer fmt.Println("၃")
defer fmt.Println("၂")
defer fmt.Println("၁")
fmt.Println("အလယ်")
}
0 သုညနဲ့ စားလို့ မရပါ 2.5 10 [2 4 6] အလယ် ၁ ၂ ၃
defer ကို ဖိုင် ဖွင့်ပြီးတာနဲ့ ချက်ချင်း ရေးထားတာ အကောင်းဆုံးပါ —
defer f.Close()။ Function က ဘယ်လို ပြီးသွားလဲဆိုတာ မခွဲခြားဘဲ
ပိတ်ပေးမှာ သေချာတယ်။
func f() (n int, err error) လို နာမည်ပေးထားရင်
return ချည်း ရေးလို့ရတယ်။ ဒါပေမယ့် function ရှည်ရင်
ဘာပြန်လဲ မရှင်းတော့ဘူး — နာမည်မပါတဲ့ return ကို ပိုသုံးသင့်တယ်။
Array, Slice, Map — ဒေတာ အစုအဝေး
Go မှာ array က အရှည် ပုံသေ၊ slice က အရှည် ပြောင်းနိုင်၊ map က key-value သိမ်းတယ်။ လက်တွေ့မှာ array ကို တိုက်ရိုက် သုံးတာ ရှားပြီး slice ကို အများဆုံး သုံးတယ်။
ဒီခန်း ပြီးရင် သိလာမယ့် အချက်များ
- Slice ဖန်တီးခြင်း၊
append,len,cap - Slice ဖြတ်ခြင်းနဲ့ underlying array
- Map ရဲ့ comma-ok idiom
- range နဲ့ လှည့်ခြင်း
ကုဒ်ဥပမာ ၁ — Slice
package main
import "fmt"
func main() {
// array — အရှည် ပုံသေ
var fixed [3]int = [3]int{10, 20, 30}
// slice — အရှည် ပြောင်းနိုင်
prices := []int{25000, 12000, 8000}
names := make([]string, 0, 3) // len 0, cap 3
prices = append(prices, 45000)
names = append(names, "မီးသီး", "ပလပ်")
fmt.Println(fixed)
fmt.Println(prices, len(prices), cap(prices))
fmt.Println(names)
// ဖြတ်ခြင်း — [start:end] (end မပါ)
fmt.Println(prices[1:3])
fmt.Println(prices[:2])
fmt.Println(prices[2:])
// ⚠ slice က underlying array ကို မျှဝေတယ်
sub := prices[0:2]
sub[0] = 99999
fmt.Println(prices[0]) // 99999 ပြောင်းသွား
// လုံးဝ ကူးချင်ရင် copy
safe := make([]int, len(prices))
copy(safe, prices)
safe[0] = 1
fmt.Println(prices[0], safe[0])
// ပေါင်းခြင်း
all := append([]int{1, 2}, []int{3, 4}...)
fmt.Println(all)
}
[10 20 30] [25000 12000 8000 45000] 4 4 [မီးသီး ပလပ်] [12000 8000] [25000 12000] [8000 45000] 99999 99999 1 [1 2 3 4]
၂။ Map
stock := map[string]int{
"bulb": 20,
"plug": 12,
}
stock["wire"] = 5
stock["plug"] += 3
fmt.Println(stock["bulb"])
// မရှိတဲ့ key — zero value ပြန်တယ် (0)
fmt.Println(stock["fan"])
// comma-ok — key ရှိ/မရှိ သိ
qty, ok := stock["fan"]
fmt.Println(qty, ok)
// ဖျက်ခြင်း
delete(stock, "bulb")
// range (အစီအစဉ် မသေချာ)
for name, q := range stock {
fmt.Println(name, q)
}
fmt.Println(len(stock))
20 0 0 false plug 15 wire 5 2
b := a[1:3] က ဒေတာ ကူးတာ မဟုတ်ဘဲ အမြင် (view) ဖြစ်တယ်။
တစ်ခုကို ပြောင်းရင် နောက်တစ်ခုမှာ ပါ ပြောင်းသွားတယ်။ သီးခြား လိုချင်ရင်
copy သို့ append([]int(nil), a...) သုံးပါ။
Struct & Method — ဒေတာနဲ့ အပြုအမူ
Go မှာ class မရှိဘူး၊ ဒါပေမယ့် struct နဲ့ ဒေတာကို စုပြီး method နဲ့ အပြုအမူ ပေးလို့ရတယ်။ ဒါက Go ရဲ့ object-ဆန်တဲ့ ပုံစံပါ။
ဒီခန်း ပြီးရင် သိလာမယ့် အချက်များ
- Struct သတ်မှတ်ခြင်းနဲ့ literal
- Value receiver နဲ့ pointer receiver
- Struct ထဲမှာ struct ထည့်ခြင်း (embedding)
String()method
ကုဒ်ဥပမာ ၁ — Product Struct
package main
import "fmt"
type Product struct {
ID int
Name string
Price int
Qty int
}
// Value receiver — မူရင်းကို မပြောင်း
func (p Product) Total() int {
return p.Price * p.Qty
}
// Pointer receiver — မူရင်းကို ပြောင်း
func (p *Product) Sell(n int) error {
if n > p.Qty {
return fmt.Errorf("လက်ကျန် မလုံလောက်ပါ: %d ခုပဲ ရှိတယ်", p.Qty)
}
p.Qty -= n
return nil
}
// String() ကို ပြင်ရင် Println က ဒါကို သုံးတယ်
func (p Product) String() string {
return fmt.Sprintf("%s (%d ကျပ်, လက်ကျန် %d)", p.Name, p.Price, p.Qty)
}
func main() {
bulb := Product{ID: 1, Name: "မီးသီး", Price: 8000, Qty: 20}
plug := Product{2, "ပလပ်", 12000, 12} // တိုက်ရိုက် အစဉ်လိုက်
fmt.Println(bulb)
fmt.Println(plug.Total())
err := bulb.Sell(5)
fmt.Println("ရောင်းပြီး:", err, "|", bulb)
err = bulb.Sell(100)
fmt.Println("မအောင်:", err, "|", bulb)
// zero value struct
var empty Product
fmt.Printf("%+v\n", empty)
}
မီးသီး (8000 ကျပ်, လက်ကျန် 20)
144000
ရောင်းပြီး: <nil> | မီးသီး (8000 ကျပ်, လက်ကျန် 15)
မအောင်: လက်ကျန် မလုံလောက်ပါ: 15 ခုပဲ ရှိတယ် | မီးသီး (8000 ကျပ်, လက်ကျန် 15)
{ID:0 Name: Price:0 Qty:0}
bulb.Sell(5) က pointer receiver ဖြစ်လို့
bulb ရဲ့ Qty က တကယ် လျော့သွားတယ်။ Go က
(&bulb).Sell(5) ကို အလိုအလျောက် လုပ်ပေးတာပါ။
၂။ Embedding — အမွေဆက်ခံမှု နေရာမှာ
type Staff struct {
Name string
Role string
}
func (s Staff) Greet() string {
return "မင်္ဂလာပါ, " + s.Name
}
// Embedding — Staff ရဲ့ field/method တွေ တိုက်ရိုက် ရလာတယ်
type Manager struct {
Staff
TeamSize int
}
func main() {
m := Manager{
Staff: Staff{Name: "Aung", Role: "Manager"},
TeamSize: 8,
}
fmt.Println(m.Name) // promoted field
fmt.Println(m.Greet()) // promoted method
fmt.Println(m.TeamSize)
}
Aung မင်္ဂလာပါ, Aung 8
- ဒေတာ မပြောင်းရင် value receiver
(p Product)။ - ပြောင်းရင် (Sell, Update) pointer receiver
(p *Product)။ - Struct ကြီးရင် ကူးယူမှု များတာမို့ pointer receiver က ပိုမြန်တယ်။
- Method တွေမှာ receiver ပုံစံ တစ်မျိုးတည်း ညီညွတ်အောင် ထားပါ။
Pointer — တန်ဖိုး မဟုတ်ဘဲ လိပ်စာ
Pointer က variable တစ်ခု သိမ်းထားတဲ့ memory လိပ်စာ ကို သိမ်းတယ်။ Function ကို struct ကြီး ကူးယူစရာ မလိုဘဲ လိပ်စာပဲ ပေးလို့ရတယ်၊ မူရင်းကို ပြောင်းလို့လည်း ရတယ်။ Go မှာ pointer arithmetic မရှိတာမို့ အန္တရာယ် နည်းတယ်။
ဒီခန်း ပြီးရင် သိလာမယ့် အချက်များ
&(လိပ်စာ ယူ) နဲ့*(တန်ဖိုး ဖတ်)- Function ထဲက မူရင်းကို ပြောင်းခြင်း
- nil pointer ကို စစ်ခြင်း
new()နဲ့ ဖန်တီးခြင်း
ကုဒ်ဥပမာ ၁ — Pointer အခြေခံ
package main
import "fmt"
type Product struct {
Name string
Price int
}
// value ကူးယူ — မူရင်း မပြောင်း
func discountCopy(p Product) {
p.Price = p.Price * 90 / 100
}
// pointer လိပ်စာ ယူ — မူရင်း ပြောင်း
func discountPtr(p *Product) {
p.Price = p.Price * 90 / 100
}
func setName(p *Product, name string) {
p.Name = name
}
func main() {
x := 10
p := &x // p က x ရဲ့ လိပ်စာ
fmt.Println(x) // 10
fmt.Println(*p) // 10 (dereference)
*p = 20
fmt.Println(x) // 20
bulb := Product{Name: "မီးသီး", Price: 8000}
discountCopy(bulb)
fmt.Println("copy:", bulb.Price)
discountPtr(&bulb)
fmt.Println("ptr:", bulb.Price)
setName(&bulb, "LED မီးသီး")
fmt.Println(bulb.Name)
// nil pointer
var empty *Product
fmt.Println(empty == nil)
if empty != nil {
fmt.Println(empty.Name)
}
// new — zero value ရှိတဲ့ pointer
np := new(Product)
np.Name = "အသစ်"
fmt.Println(np.Name)
}
10 10 20 copy: 8000 ptr: 7200 LED မီးသီး true အသစ်
Go က struct pointer အတွက် p.Name လို့ ရိုးရိုး ရေးလို့ရတယ် —
(*p).Name လို့ မရေးရပါ။ ဒါကို automatic dereference လို့ ခေါ်တယ်။
var p *Product က nil ပါ။ p.Name
ကို ဖတ်ရင် panic ဖြစ်တယ် (nil pointer dereference)။
Pointer လက်ခံတဲ့ function မှာ if p == nil { return ... }
ကို အစမှာ စစ်ပါ။
- Function က struct ကို ပြောင်းရမယ်ဆိုရင်။
- Struct က ကြီးပြီး ကူးယူမှု ရှောင်ချင်ရင်။
- “မရှိ” ဆိုတဲ့ အခြေအနေကို nil နဲ့ ဖော်ပြချင်ရင် (
*string)။ - Slice နဲ့ map က reference type ဖြစ်ပြီးသားမို့ pointer ထပ် မလိုပါ။
Interface — အပြုအမူကို သတ်မှတ်ခြင်း
Interface က “ဒီ method တွေ ရှိရမယ်” လို့ သတ်မှတ်တယ်။ Go မှာ
implements လို့ ရေးစရာ မလိုဘဲ method တွေ ပြည့်စုံရင်
အလိုအလျောက် ကိုက်ညီတယ်။ ဒါက ကုဒ် ဆက်စပ်မှုကို လျှော့ချပေးတယ်။
ဒီခန်း ပြီးရင် သိလာမယ့် အချက်များ
- Interface သတ်မှတ်ခြင်းနဲ့ implicit implementation
- Interface ကို parameter အဖြစ် သုံးခြင်း
- Type assertion နဲ့ type switch
anyနဲ့error
ကုဒ်ဥပမာ ၁ — Shape Interface
package main
import (
"fmt"
"math"
)
type Shape interface {
Area() float64
Name() string
}
type Circle struct {
R float64
}
func (c Circle) Area() float64 { return math.Pi * c.R * c.R }
func (c Circle) Name() string { return "အဝိုင်း" }
type Rect struct {
W, H float64
}
func (r Rect) Area() float64 { return r.W * r.H }
func (r Rect) Name() string { return "စတုဂံ" }
// interface ကို လက်ခံ — ဘယ် shape မဆို ရ
func describe(s Shape) {
fmt.Printf("%s ရဲ့ ဧရိယာ: %.2f\n", s.Name(), s.Area())
}
func main() {
shapes := []Shape{
Circle{R: 2},
Rect{W: 3, H: 4},
}
total := 0.0
for _, s := range shapes {
describe(s)
total += s.Area()
}
fmt.Printf("စုစုပေါင်း: %.2f\n", total)
// type assertion
var s Shape = Circle{R: 1}
if c, ok := s.(Circle); ok {
fmt.Println("အချင်းဝက်:", c.R)
}
// type switch
var v any = 42
switch x := v.(type) {
case int:
fmt.Println("int:", x+1)
case string:
fmt.Println("string:", x)
default:
fmt.Println("အခြား")
}
}
အဝိုင်း ရဲ့ ဧရိယာ: 12.57 စတုဂံ ရဲ့ ဧရိယာ: 12.00 စုစုပေါင်း: 24.57 အချင်းဝက်: 1 int: 43
Circle က Shape ကို “သတ်မှတ်ကြေညာ”
ထားတာ မဟုတ်ပါဘူး — Area() နဲ့ Name()
ရှိရုံနဲ့ အလိုအလျောက် ကိုက်ညီသွားတာပါ။ Interface ကို သေးသေးလေး ထားတာ
Go ရဲ့ အလေ့အထ ကောင်းပါ။
error—Error() stringmethod တစ်ခုတည်း။fmt.Stringer—String() string။io.Writer—Write([]byte) (int, error)။ ဖိုင်၊ network၊ buffer အားလုံး ကိုက်ညီတယ်။any—interface{}ရဲ့ အမည်တူ (Go 1.18+)။ တိကျတဲ့ type မသိရင် သုံးပါ။
Error Handling — မှားတာကို ရှင်းရှင်းလင်းလင်း ကိုင်တွယ်ခြင်း
Go မှာ exception မရှိပါဘူး။ Error က တန်ဖိုး တစ်မျိုးပါ — error
interface ပြန်ပေးပြီး if err != nil နဲ့ စစ်တယ်။
ဒါက ဘယ်နေရာမှာ ဘာ မှားနိုင်လဲ ဆိုတာ ကုဒ်ထဲမှာ မြင်သာစေတယ်။
ဒီခန်း ပြီးရင် သိလာမယ့် အချက်များ
errors.Newနဲ့fmt.Errorf- Error wrapping (
%w) နဲ့errors.Is - Custom error type
panic/recoverကို ဘယ်အခါ သုံးမလဲ
ကုဒ်ဥပမာ ၁ — Error ကို ပြန်ပေးခြင်း
package main
import (
"errors"
"fmt"
)
// sentinel error — တိုက်ရိုက် နှိုင်းယှဉ်ဖို့
var ErrOutOfStock = errors.New("လက်ကျန် မရှိ")
type Product struct {
Name string
Qty int
}
func (p *Product) Take(n int) error {
if n <= 0 {
return fmt.Errorf("အရေအတွက် မမှန်: %d", n)
}
if p.Qty < n {
return fmt.Errorf("%s: %w (လက်ကျန် %d)", p.Name, ErrOutOfStock, p.Qty)
}
p.Qty -= n
return nil
}
func main() {
bulb := &Product{Name: "မီးသီး", Qty: 2}
if err := bulb.Take(1); err != nil {
fmt.Println("error:", err)
} else {
fmt.Println("ရောင်းပြီး, လက်ကျန်", bulb.Qty)
}
err := bulb.Take(5)
fmt.Println("error:", err)
// %w နဲ့ ခြုံထားတာကို errors.Is နဲ့ စစ်
fmt.Println(errors.Is(err, ErrOutOfStock))
// custom error type
type ValidationError struct {
Field string
}
var ve ValidationError
err2 := fmt.Errorf("ဖောင် မမှန်: %w", ve)
fmt.Println(err2)
}
ရောင်းပြီး, လက်ကျန် 1
error: မီးသီး: လက်ကျန် မရှိ (လက်ကျန် 1)
true
ဖောင် မမှန်: {}
panic က program ကို ရပ်တယ် — programmer ရဲ့ အမှား
(index ကျော်၊ nil dereference) လို မဖြစ်သင့်တဲ့ အခြေအနေအတွက်သာ။
recover ကို HTTP handler တွေမှာ server မရပ်စေရန်
middleware အနေနဲ့ သုံးတတ်တယ်။ ပုံမှန် လုပ်ငန်း error တွေအတွက်တော့
error ကို ပြန်ပေးပါ။
- Error ကို လျစ်လျူ မရှုပါနဲ့ —
_နဲ့ ဖျောက်တာက bug ဝှက်တာ။ - Error ကို ခြုံပြီး ပြန်ပေးတဲ့အခါ
%wကို သုံးပါ —errors.Isက အတွင်းကို ရှာနိုင်တယ်။ - Error message က စာလုံးအသေးနဲ့ စပါ၊ အဆုံးမှာ ပုဒ်မ မထည့်ပါ (Go ရဲ့ စံ)။
Goroutine & Channel — တစ်ချိန်တည်း အလုပ်လုပ်ခြင်း
Go ရဲ့ အကြီးမားဆုံး အားသာချက်က concurrency ပါ။ go
စာလုံး တစ်လုံး ထည့်လိုက်ရင် function တစ်ခုက သီးခြား goroutine အဖြစ်
တစ်ချိန်တည်း run တယ်။ Channel နဲ့ သူတို့ကြား ဒေတာ ဖလှယ်တယ်။
ဒီခန်း ပြီးရင် သိလာမယ့် အချက်များ
goနဲ့ goroutine စတင်ခြင်းsync.WaitGroupနဲ့ စောင့်ခြင်း- Unbuffered/buffered channel
selectနဲ့ mutex
ကုဒ်ဥပမာ ၁ — Goroutine နဲ့ Channel
package main
import (
"fmt"
"sync"
"time"
)
func main() {
// channel — goroutine တွေကြား ဒေတာ ဖလှယ်
done := make(chan string)
go func () {
time.Sleep(100 * time.Millisecond)
done <- "အလုပ် ပြီးပါပြီ"
}()
fmt.Println("စောင့်နေတယ်...")
msg := <-done // ဒေတာ မရောက်မချင်း စောင့်
fmt.Println(msg)
// WaitGroup — goroutine အားလုံး ပြီးတာကို စောင့်
var wg sync.WaitGroup
results := make(chan int, 3)
for i := 1; i <= 3; i++ {
wg.Add(1)
go func (n int) {
defer wg.Done()
results <- n * n
}(i)
}
wg.Wait()
close(results)
total := 0
for r := range results {
total += r
}
fmt.Println("စုစုပေါင်း:", total)
// select — channel များစွာထဲက အရင် ရောက်တာကို ယူ
a := make(chan string)
b := make(chan string)
go func () { time.Sleep(50 * time.Millisecond); a <- "A" }()
go func () { time.Sleep(80 * time.Millisecond); b <- "B" }()
select {
case v := <-a:
fmt.Println("အရင် ရောက်:", v)
case v := <-b:
fmt.Println("အရင် ရောက်:", v)
case <-time.After(1 * time.Second):
fmt.Println("timeout")
}
}
စောင့်နေတယ်... အလုပ် ပြီးပါပြီ စုစုပေါင်း: 14 အရင် ရောက်: A
Channel က chan T လို့ ရေးတယ်။ ch <- v က
ပို့တာ၊ v := <-ch က ယူတာ။ Unbuffered channel မှာ
ပို့တဲ့ဘက်နဲ့ ယူတဲ့ဘက် နှစ်ဖက်လုံး ရှိမှ အလုပ်ဖြစ်တယ် — ဒါက synchronize ဖြစ်စေတယ်။
၂။ Mutex — မျှဝေ ဒေတာ ကာကွယ်ခြင်း
type Counter struct {
mu sync.Mutex
n int
}
func (c *Counter) Inc() {
c.mu.Lock()
defer c.mu.Unlock()
c.n++
}
func main() {
var c Counter
var wg sync.WaitGroup
for i := 0; i < 1000; i++ {
wg.Add(1)
go func () {
defer wg.Done()
c.Inc()
}()
}
wg.Wait()
fmt.Println(c.n) // တိတိကျကျ 1000
}
1000
Goroutine နှစ်ခုက variable တစ်ခုကို တစ်ချိန်တည်း ရေး/ဖတ်ရင် data race ဖြစ်တယ်။
go run -race main.go နဲ့ စမ်းပါ။
ဖြေရှင်းနည်းက mutex သို့ channel — “memory ကို မမျှဝေဘဲ channel နဲ့ ပို့ပါ” ဆိုတာ
Go ရဲ့ ဆောင်ပုဒ်ပါ။
Package & Module — ကုဒ်ကို စနစ်တကျ ခွဲခြင်း
ဖိုင် တစ်ခုတည်းမှာ ကုဒ် အားလုံး ထည့်ရင် ကြီးလာတာနဲ့ ရှုပ်လာတယ်။ Package က
ဆက်စပ်တဲ့ ကုဒ်တွေကို စုပေးတယ်။ Module (go.mod) က
project တစ်ခုလုံးရဲ့ အမည်နဲ့ dependency တွေကို စီမံတယ်။
ဒီခန်း ပြီးရင် သိလာမယ့် အချက်များ
go mod initနဲ့ module စခြင်း- Exported / unexported (စာလုံးအကြီး/အသေး)
- Local package ကို import ခြင်း
- Project folder ဖွဲ့စည်းပုံ
၁။ ဖွဲ့စည်းပုံ
shop/
├── go.mod
├── main.go
└── price/
└── price.go
mkdir shop && cd shop
go mod init example.com/shop
mkdir price
၂။ Package ဖိုင်
package price
import "fmt"
const VAT = 0.05
// Exported — စာလုံးအကြီး စ → အပြင်က ခေါ်လို့ရ
func WithVAT(amount float64) float64 {
return amount * (1 + VAT)
}
// unexported — စာလုံးအသေး စ → ဒီ package ထဲသာ
func label(amount float64) string {
return fmt.Sprintf("%.2f ကျပ်", amount)
}
func Label(amount float64) string {
return label(amount)
}
package main
import (
"fmt"
"example.com/shop/price"
)
func main() {
total := price.WithVAT(20000)
fmt.Println(price.Label(total))
fmt.Println(price.VAT)
}
21000.00 ကျပ် 0.05
go mod tidy— သုံးတဲ့ dependency ကို ထည့်၊ မသုံးတာကို ဖျက်။go get github.com/gin-gonic/gin— package ယူ။go list -m all— dependency စာရင်း။- Package အမည်က အတို၊ အသေး၊ အဓိပ္ပာယ်ရှိ —
price,db,api။
File & JSON — ဒေတာ သိမ်းခြင်း
Program ပိတ်လိုက်ရင် memory ထဲက ဒေတာ ပျောက်တယ်။ ဖိုင်ထဲ သိမ်းချင်ရင်
os package ကို သုံးတယ်။ ဒေတာကို ဖိုင်နဲ့ အခြား service
တွေကြား ဖလှယ်ဖို့ JSON က စံဖြစ်တယ်။
ဒီခန်း ပြီးရင် သိလာမယ့် အချက်များ
os.ReadFile/os.WriteFilejson.Marshal/Unmarshal- Struct tag နဲ့ JSON key သတ်မှတ်ခြင်း
- Error ကို မမေ့ဘဲ စစ်ခြင်း
ကုဒ်ဥပမာ ၁ — JSON သိမ်း/ဖတ်
package main
import (
"encoding/json"
"fmt"
"os"
)
type Product struct {
ID int `json:"id"`
Name string `json:"name"`
Price int `json:"price"`
Qty int `json:"qty,omitempty"`
}
func main() {
products := []Product{
{ID: 1, Name: "မီးသီး", Price: 8000, Qty: 20},
{ID: 2, Name: "ပလပ်", Price: 12000, Qty: 0},
}
// struct → JSON bytes
data, err := json.MarshalIndent(products, "", " ")
if err != nil {
fmt.Println("marshal error:", err)
return
}
// ဖိုင်ထဲ ရေး
if err := os.WriteFile("products.json", data, 0644); err != nil {
fmt.Println("write error:", err)
return
}
fmt.Println("သိမ်းပြီး, bytes:", len(data))
// ဖိုင် ပြန်ဖတ်
raw, err := os.ReadFile("products.json")
if err != nil {
fmt.Println("read error:", err)
return
}
var loaded []Product
if err := json.Unmarshal(raw, &loaded); err != nil {
fmt.Println("unmarshal error:", err)
return
}
for _, p := range loaded {
fmt.Printf("%d. %s — %d ကျပ်\n", p.ID, p.Name, p.Price)
}
}
သိမ်းပြီး, bytes: 137 1. မီးသီး — 8000 ကျပ် 2. ပလပ် — 12000 ကျပ်
json:"name" က struct tag ပါ — Go field အမည်နဲ့ JSON key မတူရင်
သတ်မှတ်တယ်။ omitempty က zero value ဖြစ်ရင် key ကို
ချန်ထားတယ်။ Unmarshal လုပ်တဲ့အခါ pointer (&loaded)
ပေးရတာ မမေ့ပါနဲ့။
os.WriteFile(path, data, 0644) မှာ 0644 က
ပိုင်ရှင် ဖတ်/ရေး၊ ကျန်သူ ဖတ်လို့ရ ဆိုတာ။ လျှို့ဝှက်ချက် ဖိုင်အတွက် 0600 ကို သုံးပါ။
Windows မှာ permission က အကန့်အသတ် ရှိပေမယ့် Linux server အတွက် အရေးကြီးတယ်။
HTTP Server — web API ဆောက်ခြင်း
Go ရဲ့ standard library မှာ HTTP server ပါပြီးသားပါ။ Framework မလိုဘဲ handler ရေးပြီး JSON API ဆောက်လို့ရတယ်။ ဒါက Go ကို backend မှာ လူကြိုက်များစေတဲ့ အကြောင်းရင်းပါ။
ဒီခန်း ပြီးရင် သိလာမယ့် အချက်များ
http.NewServeMuxနဲ့ route သတ်မှတ်ခြင်း- Handler function ရဲ့
wနဲ့r - JSON response ပြန်ခြင်း
- Method နဲ့ status code ကိုင်တွယ်ခြင်း
ကုဒ်ဥပမာ ၁ — Items API
package main
import (
"encoding/json"
"log"
"net/http"
)
type Item struct {
ID int `json:"id"`
Name string `json:"name"`
}
var items = []Item{
{ID: 1, Name: "မီးသီး"},
{ID: 2, Name: "ပလပ်"},
}
func listItems(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
json.NewEncoder(w).Encode(items)
}
func createItem(w http.ResponseWriter, r *http.Request) {
var it Item
if err := json.NewDecoder(r.Body).Decode(&it); err != nil {
http.Error(w, "JSON မမှန်ပါ", http.StatusBadRequest)
return
}
if it.Name == "" {
http.Error(w, "name လိုအပ်ပါတယ်", http.StatusBadRequest)
return
}
it.ID = len(items) + 1
items = append(items, it)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(it)
}
func main() {
mux := http.NewServeMux()
// Go 1.22+ — method ပါ ပါတဲ့ pattern
mux.HandleFunc("GET /items", listItems)
mux.HandleFunc("POST /items", createItem)
log.Println("server: http://localhost:8080")
log.Fatal(http.ListenAndServe(":8080", mux))
}
$ curl http://localhost:8080/items
[{"id":1,"name":"မီးသီး"},{"id":2,"name":"ပလပ်"}]
$ curl -X POST http://localhost:8080/items \
-H "Content-Type: application/json" \
-d '{"name":"ကြိုး"}'
{"id":3,"name":"ကြိုး"}
$ curl -i http://localhost:8080/items
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
http.ResponseWriter က response ရေးတဲ့ နေရာ၊
*http.Request က ရောက်လာတဲ့ တောင်းဆိုမှု။
WriteHeader ကို body မရေးခင် ခေါ်ရတယ်။
JSON မှာ မြန်မာစာ မှန်ဖို့ charset=utf-8 ကို ထည့်ပါ။
- Request body အရွယ် ကန့်သတ်ပါ —
http.MaxBytesReader။ - Input ကို အမြဲ စစ်ပါ — method, required field, အရှည်။
- Production မှာ
http.Serverရဲ့ ReadTimeout/WriteTimeout ကို သတ်မှတ်ပါ။ - Error အပြည့်အစုံ (stack, SQL) ကို client ကို မပြပါနဲ့ — log မှာသာ ထားပါ။
Testing — ကုဒ် မှန်/မမှန် စစ်ခြင်း
Go မှာ testing ပါပြီးသား — framework မလိုဘူး။ _test.go
ဖိုင် ဆောက်ပြီး go test ရိုက်ရုံပါ။ Code ပြင်တိုင်း
test ကို ပြန်လိုက်ရင် ယုံကြည်မှု ရှိလာတယ်။
ဒီခန်း ပြီးရင် သိလာမယ့် အချက်များ
_test.goဖိုင် ဖွဲ့စည်းပုံtesting.Tနဲ့ error ပြခြင်း- Table-driven test
go testရဲ့ flag များ
၁။ စမ်းစရာ ကုဒ်
package calc
func Total(price, qty int) int {
if qty < 0 {
return 0
}
return price * qty
}
func Discount(total, percent int) int {
if percent < 0 {
percent = 0
}
if percent > 100 {
percent = 100
}
return total - total*percent/100
}
၂။ Test ဖိုင်
package calc
import "testing"
func TestTotal(t *testing.T) {
tests := []struct {
name string
price int
qty int
want int
}{
{"2 items", 25000, 2, 50000},
{"0 items", 25000, 0, 0},
{"negative", 25000, -1, 0},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := Total(tt.price, tt.qty)
if got != tt.want {
t.Errorf("Total(%d, %d) = %d; want %d",
tt.price, tt.qty, got, tt.want)
}
})
}
}
func TestDiscount(t *testing.T) {
if got := Discount(50000, 10); got != 45000 {
t.Errorf("Discount = %d; want 45000", got)
}
if got := Discount(50000, 150); got != 0 {
t.Errorf("150%% discount = %d; want 0", got)
}
}
=== RUN TestTotal
=== RUN TestTotal/2_items
=== RUN TestTotal/0_items
=== RUN TestTotal/negative
--- PASS: TestTotal (0.00s)
--- PASS: TestTotal/2_items (0.00s)
--- PASS: TestTotal/0_items (0.00s)
--- PASS: TestTotal/negative (0.00s)
=== RUN TestDiscount
--- PASS: TestDiscount (0.00s)
PASS
ok example.com/shop/calc 0.002s
go test ./...— package အားလုံး စမ်း။go test -v— test တစ်ခုချင်း ရလဒ် ပြ။go test -run TestTotal— နာမည် ကိုက်တာပဲ။go test -cover— ဘယ်လောက် ဖုံးလွှမ်းလဲ။
Mini Project — ပစ္စည်းစာရင်း REST API
သင်ခဲ့တာတွေ ပေါင်းပြီး CRUD (Create, Read, Update, Delete) လုပ်နိုင်တဲ့
ပစ္စည်းစာရင်း API လေး ဆောက်မယ်။ Struct၊ method၊ interface (error)၊
mutex၊ JSON နဲ့ HTTP handler အားလုံး ပါတယ်။
ဒီခန်း ပြီးရင် လုပ်နိုင်မယ့် အရာ
- REST ပုံစံ route တွေ သတ်မှတ်ခြင်း
- In-memory store ကို mutex နဲ့ ကာကွယ်ခြင်း
- Status code မှန်ကန်စွာ ပြန်ခြင်း
- curl နဲ့ API ကို စမ်းသပ်ခြင်း
၁။ အပြည့်အစုံ ကုဒ်
package main
import (
"encoding/json"
"errors"
"log"
"net/http"
"strconv"
"sync"
)
type Item struct {
ID int `json:"id"`
Name string `json:"name"`
Price int `json:"price"`
Qty int `json:"qty"`
}
type Store struct {
mu sync.Mutex
items map[int]Item
next int
}
var ErrNotFound = errors.New("ပစ္စည်း မတွေ့ပါ")
func NewStore() *Store {
return &Store{
items: map[int]Item{
1: {ID: 1, Name: "မီးသီး", Price: 8000, Qty: 20},
},
next: 2,
}
}
func (s *Store) List() []Item {
s.mu.Lock()
defer s.mu.Unlock()
out := make([]Item, 0, len(s.items))
for _, it := range s.items {
out = append(out, it)
}
return out
}
func (s *Store) Create(it Item) Item {
s.mu.Lock()
defer s.mu.Unlock()
it.ID = s.next
s.next++
s.items[it.ID] = it
return it
}
func (s *Store) Update(id int, it Item) (Item, error) {
s.mu.Lock()
defer s.mu.Unlock()
old, ok := s.items[id]
if !ok {
return Item{}, ErrNotFound
}
it.ID = id
it.Name = old.Name
s.items[id] = it
return it, nil
}
func (s *Store) Delete(id int) error {
s.mu.Lock()
defer s.mu.Unlock()
if _, ok := s.items[id]; !ok {
return ErrNotFound
}
delete(s.items, id)
return nil
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
json.NewEncoder(w).Encode(v)
}
func main() {
store := NewStore()
mux := http.NewServeMux()
mux.HandleFunc("GET /items", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, store.List())
})
mux.HandleFunc("POST /items", func(w http.ResponseWriter, r *http.Request) {
var it Item
if err := json.NewDecoder(r.Body).Decode(&it); err != nil || it.Name == "" {
http.Error(w, "name လိုအပ်ပါတယ်", http.StatusBadRequest)
return
}
writeJSON(w, http.StatusCreated, store.Create(it))
})
mux.HandleFunc("PUT /items/{id}", func(w http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(r.PathValue("id"))
if err != nil {
http.Error(w, "id မမှန်", http.StatusBadRequest)
return
}
var it Item
if err := json.NewDecoder(r.Body).Decode(&it); err != nil {
http.Error(w, "JSON မမှန်", http.StatusBadRequest)
return
}
updated, err := store.Update(id, it)
if errors.Is(err, ErrNotFound) {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
writeJSON(w, http.StatusOK, updated)
})
mux.HandleFunc("DELETE /items/{id}", func(w http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(r.PathValue("id"))
if err != nil {
http.Error(w, "id မမှန်", http.StatusBadRequest)
return
}
if err := store.Delete(id); errors.Is(err, ErrNotFound) {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
w.WriteHeader(http.StatusNoContent)
})
log.Println("API: http://localhost:8080/items")
log.Fatal(http.ListenAndServe(":8080", mux))
}
၂။ စမ်းသပ်ခြင်း
$ curl http://localhost:8080/items
[{"id":1,"name":"မီးသီး","price":8000,"qty":20}]
$ curl -X POST http://localhost:8080/items \
-H "Content-Type: application/json" \
-d '{"name":"ပလပ်","price":12000,"qty":10}'
{"id":2,"name":"ပလပ်","price":12000,"qty":10}
$ curl -X PUT http://localhost:8080/items/2 \
-H "Content-Type: application/json" \
-d '{"price":13000,"qty":8}'
{"id":2,"name":"ပလပ်","price":13000,"qty":8}
$ curl -i -X DELETE http://localhost:8080/items/1
HTTP/1.1 204 No Content
$ curl -i http://localhost:8080/items/99
(route မရှိရင် 405/404 — method နဲ့ path ကို စစ်ပါ)
- ဒေတာကို JSON ဖိုင် သို့ SQLite မှာ သိမ်းပါ (server ပိတ်ရင် မပျောက်စေရန်)။
- GET /items/{id} ကို ထပ်ဖြည့်ပါ —
ErrNotFoundကို 404 ပြန်ပါ။ - Handler တွေအတွက်
httptestနဲ့ test ရေးပါ။ - Pagination (
?page=1&limit=20) နဲ့ ရှာဖွေမှု ထည့်ပါ။
Go အခြေခံ ကနေ REST API တစ်ခု ဆောက်နိုင်တဲ့အထိ ရောက်ပါပြီ။
နောက်ထပ် JavaScript နဲ့ frontend ကို ချိတ်ပြီး
fetch နဲ့ ဒီ API ကို ခေါ်ကြည့်ပါ။ Python ကို ဆက်လေ့လာချင်ရင်
Python သင်ခန်းစာ ကို ကြည့်ပါ။