Thuta Learning
Go
AdvancedProgrammingအခြေခံ

HTTP & JSON API Fundamentals

Goသင်ခန်းစာ 2435 မိနစ်

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • http.ServeMux မှာ "GET /tasks/{id}" လို method + wildcard pattern တွေကို register လုပ်ပြီး r.PathValue နဲ့ တန်ဖိုး ယူနိုင်ဖို့
  • json.NewDecoder နဲ့ request body ကို struct ထဲ decode လုပ်ပြီး မှားတဲ့ input ကို 400 နဲ့ ငြင်းနိုင်ဖို့
  • Header, status code, body ကို မှန်ကန်တဲ့ အစီအစဉ်အတိုင်း ရေးတဲ့ writeJSON helper တစ်ခု ရေးနိုင်ဖို့
  • httptest.NewServer နဲ့ httptest.NewRecorder ကို သုံးပြီး handler တွေကို in-process စမ်းသပ်နိုင်ဖို့

ရိုးရိုးလေး ရှင်းပြမယ်

HTTP JSON API ကို ရိုးရိုးလေး ပြောရရင်

JSON API ဆိုတာ စားသောက်ဆိုင်က ကောင်တာနဲ့ တူပါတယ်။ Client က order စာရွက် (HTTP request) ပို့ပါတယ်: ဘာလုပ်ချင်လဲ (GET, POST)၊ ဘယ်ဟာကို လိုချင်လဲ (/tasks/1) နဲ့ လိုအပ်ရင် အသေးစိတ် (JSON body)။ Server က အဖြေတစ်ခု (response) ပြန်ပေးပါတယ်: ရလဒ်ကို ပြောတဲ့ status code တစ်ခုနဲ့ JSON body တစ်ခုပါ။

Go မှာ ဒါကို လုပ်ဖို့ framework မလိုပါဘူး။ net/http က route တွေကို handler function တွေနဲ့ ချိတ်ပေးပြီး encoding/json က Go struct တွေနဲ့ JSON ကြား ပြောင်းပေးပါတယ်။ httptest package ကတော့ ဒီ server ကို အင်တာနက် မလိုဘဲ program တစ်ခုတည်းထဲမှာ စမ်းလို့ ရအောင် လုပ်ပေးပါတယ်။

Problem → Why → Solution

ပြဿနာ: 'အလုပ်လုပ်တယ်' လို့ ထင်ရတဲ့ handler

အောက်က handler ကို browser ကနေ စမ်းတော့ task ကို ပြန်ရပါတယ်။ ဒါပေမဲ့ mobile app team က report တွေ ပို့လာပါတယ်: မရှိတဲ့ task ကို တောင်းရင် status 200 နဲ့ အလွတ် object ရတယ်၊ DELETE ပို့လည်း GET လို ဖြေတယ်၊ JSON parse မရတဲ့အခါ client က ဘာမှားလဲ မသိရဘူး။ Response က Content-Type: application/json ဆိုတာလည်း မပါပါဘူး။

handler_bad.go
var tasks = map[string]Task{} // shared by every request, no lock

func taskHandler(w http.ResponseWriter, r *http.Request) {
    id := strings.TrimPrefix(r.URL.Path, "/tasks/") // any method lands here
    task := tasks[id]                                // missing id -> zero Task
    data, _ := json.Marshal(task)                    // error ignored
    w.Write(data)                                    // always 200, no Content-Type
}

API တစ်ခုအတွက် ဘာကြောင့် အရေးကြီးလဲ

API ကို ခေါ်တဲ့ program က လူမဟုတ်ပါဘူး၊ status code နဲ့ body shape ကိုပဲ ကြည့်ပြီး ဆုံးဖြတ်ပါတယ်။ 404 အစား 200 ပြန်ရင် client က အလွတ် task ကို တကယ့် data လို ပြသပါလိမ့်မယ်။ Method, status code, Content-Type နဲ့ error body ဆိုတာ client နဲ့ server ကြားက contract ပါ၊ handler တိုင်းက အဲဒီ contract ကို ထိန်းရပါမယ်။

Core concept: route, decode, respond

net/http မှာ handler ဆိုတာ func(w http.ResponseWriter, r *http.Request) signature ရှိတဲ့ function ပါ။ r က client ပို့လိုက်တာ အားလုံး (method, URL, header, body) ကို သယ်ဆောင်ပြီး w ကတော့ response ကို ရေးတဲ့ နေရာပါ။ http.ServeMux က request တစ်ခုစီကို pattern နဲ့ တိုက်ပြီး ကိုက်ညီတဲ့ handler ကို ခေါ်ပေးတဲ့ router ပါ။ Go 1.22 ကစပြီး pattern ထဲမှာ method နဲ့ wildcard ကို တိုက်ရိုက် ရေးလို့ ရပါတယ်: "GET /tasks/{id}" က GET (နဲ့ HEAD) request တွေကိုပဲ လက်ခံပြီး {id} နေရာက တန်ဖိုးကို r.PathValue("id") နဲ့ ပြန်ယူပါတယ်။ Path ကိုက်ပေမဲ့ method မကိုက်ရင် mux က 405 Method Not Allowed ကို ကိုယ်တိုင် ပြန်ပေးပါတယ်။

JSON body ကို ဖတ်ဖို့ json.NewDecoder(r.Body).Decode(&v) ကို သုံးပါတယ်။ Decode က JSON key တွေကို struct field ရဲ့ json tag တွေနဲ့ တိုက်ပါတယ်၊ export လုပ်ထားတဲ့ (စာလုံးကြီးနဲ့ စတဲ့) field တွေကိုပဲ ဖြည့်ပေးပါတယ်။ JSON ပုံစံ မှားရင် error ပြန်ပေမဲ့ field ပျောက်နေတာကိုတော့ error မပေးပါဘူး၊ zero value ပဲ ကျန်ခဲ့ပါတယ်။ ဒါကြောင့် decode ပြီးရင် title အလွတ် ဖြစ်မဖြစ်လို business rule တွေကို ကိုယ်တိုင် စစ်ရပါတယ်။

Response ကို ရေးတဲ့ အစီအစဉ်က အရေးကြီးပါတယ်: ပထမ w.Header().Set(...) နဲ့ header တွေ၊ ဒုတိယ w.WriteHeader(status)၊ နောက်ဆုံးမှ body။ Body ကို ရေးလိုက်တာနဲ့ header နဲ့ status က client ဆီ ထွက်သွားပြီ ဖြစ်လို့ နောက်မှ ပြောင်းလို့ မရတော့ပါဘူး။ WriteHeader မခေါ်ဘဲ body ရေးရင် 200 ကို အလိုအလျောက် သုံးပါတယ်။ ဒီ အစီအစဉ်ကို writeJSON လို helper တစ်ခုထဲ ထည့်ထားရင် handler တိုင်း မှန်ကန်စွာ လိုက်နာပါတယ်။

Pattern နှစ်ခုလုံး request တစ်ခုနဲ့ ကိုက်တဲ့အခါ ပိုတိကျတဲ့ pattern က အနိုင်ရပါတယ်: GET /tasks/new က GET /tasks/{id} ထက် ပိုတိကျလို့ /tasks/new ဆိုရင် ပထမ handler ကို ခေါ်ပါတယ်။ ဘယ်ဟာမှ ပိုမတိကျဘဲ အချင်းချင်း conflict ဖြစ်တဲ့ pattern နှစ်ခုကို register လုပ်ရင် ServeMux က register လုပ်တဲ့အချိန်မှာပဲ panic ဖြစ်လို့ အမှားကို server စတာနဲ့ ချက်ချင်း သိရပါတယ်။

Statusဘယ်အချိန် ပြန်မလဲ
200 OKတောင်းတာကို အောင်မြင်စွာ ပြန်ပေးတဲ့အခါ
201 CreatedPOST က resource အသစ် ဖန်တီးလိုက်တဲ့အခါ
400 Bad RequestJSON ဒါမှမဟုတ် path တန်ဖိုး ပုံစံ မှားတဲ့အခါ
404 Not FoundID နဲ့ ကိုက်တဲ့ resource မရှိတဲ့အခါ
405 Method Not AllowedPath ရှိပေမဲ့ method ကို မထောက်ပံ့တဲ့အခါ (mux က ပြန်ပေး)
Request တစ်ခုရဲ့ ခရီးစဉ်
  1. Mux က method + path ကို တိုက်တယ်
  2. Handler က path နဲ့ body ကို ဖတ်တယ်
  3. Input ကို စစ်ပြီး error ဆို 4xx ပြန်
  4. Header, status, JSON body ကို ရေး

Error response ရေးပြီးတိုင်း return လုပ်ပါ။ မဟုတ်ရင် handler က ဆက် run ပြီး success body ကိုပါ ထပ်ရေးမိပါလိမ့်မယ်။

အထွေထွေ ပုံစံ

go
mux := http.NewServeMux()
mux.HandleFunc("METHOD /resource/{name}", handler)

func handler(w http.ResponseWriter, r *http.Request) {
    value := r.PathValue("name")
    var in InputType
    if err := json.NewDecoder(r.Body).Decode(&in); err != nil { /* 400 */ return }
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(statusCode)
    json.NewEncoder(w).Encode(result)
}

Pattern က method, path နဲ့ wildcard ကို တစ်ခါတည်း ကြေညာပါတယ်။ Handler ထဲမှာ path value နဲ့ body ကို ဖတ်၊ စစ်ပြီး header၊ status၊ body ဆိုတဲ့ အစီအစဉ်အတိုင်း ပြန်ရေးပါ။

Worked example: task API တစ်ခုနဲ့ request ခြောက်ခု

အောက်က program မှာ task တစ်ခု ဖန်တီးတဲ့ POST /tasks နဲ့ ID နဲ့ ရှာတဲ့ GET /tasks/{id} ဆိုတဲ့ route နှစ်ခု ပါပါတယ်။ httptest.NewServer က local test port ပေါ်မှာ HTTP server အစစ်တစ်ခုကို ဖွင့်ပေးပြီး main က srv.Client() နဲ့ request ခြောက်ခု ပို့ပါတယ်: အောင်မြင်တဲ့ case နှစ်ခုနဲ့ error case လေးခုပါ။ Output line တစ်ကြောင်းစီက request၊ status code နဲ့ response body ကို ပြပါတယ်။

task_api.go
package main

import (
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "net/http/httptest"
    "strconv"
    "strings"
    "sync"
)

type Task struct {
    ID    int    `json:"id"`
    Title string `json:"title"`
    Done  bool   `json:"done"`
}

type TaskStore struct {
    mu     sync.Mutex
    nextID int
    tasks  map[int]Task
}

func writeJSON(w http.ResponseWriter, status int, v any) {
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(status)
    json.NewEncoder(w).Encode(v)
}

func (s *TaskStore) create(w http.ResponseWriter, r *http.Request) {
    var in struct {
        Title string `json:"title"`
    }
    if err := json.NewDecoder(r.Body).Decode(&in); err != nil || in.Title == "" {
        writeJSON(w, http.StatusBadRequest,
            map[string]string{"error": "title is required"})
        return
    }
    s.mu.Lock()
    s.nextID++
    task := Task{ID: s.nextID, Title: in.Title}
    s.tasks[task.ID] = task
    s.mu.Unlock()
    writeJSON(w, http.StatusCreated, task)
}

func (s *TaskStore) get(w http.ResponseWriter, r *http.Request) {
    id, err := strconv.Atoi(r.PathValue("id"))
    if err != nil {
        writeJSON(w, http.StatusBadRequest,
            map[string]string{"error": "id must be a number"})
        return
    }
    s.mu.Lock()
    task, ok := s.tasks[id]
    s.mu.Unlock()
    if !ok {
        writeJSON(w, http.StatusNotFound, map[string]string{"error": "task not found"})
        return
    }
    writeJSON(w, http.StatusOK, task)
}

func main() {
    store := &TaskStore{tasks: map[int]Task{}}
    mux := http.NewServeMux()
    mux.HandleFunc("POST /tasks", store.create)
    mux.HandleFunc("GET /tasks/{id}", store.get)

    srv := httptest.NewServer(mux) // real HTTP server on a local test port
    defer srv.Close()

    call := func(method, path, body string) {
        req, _ := http.NewRequest(method, srv.URL+path, strings.NewReader(body))
        res, err := srv.Client().Do(req)
        if err != nil {
            fmt.Println("request failed:", err)
            return
        }
        defer res.Body.Close()
        data, _ := io.ReadAll(res.Body)
        fmt.Printf("%s %s -> %d %s", method, path, res.StatusCode, data)
    }

    call("POST", "/tasks", `{"title":"write tests"}`)
    call("GET", "/tasks/1", "")
    call("GET", "/tasks/42", "")
    call("GET", "/tasks/abc", "")
    call("POST", "/tasks", `{"title":""}`)
    call("DELETE", "/tasks/1", "")
}

Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်

  1. Method + wildcard routesmux.HandleFunc("GET /tasks/{id}", store.get)

    Pattern က GET ကိုပဲ လက်ခံပြီး {id} က path segment တစ်ခုကို ဖမ်းပါတယ်။ DELETE /tasks/1 က path ကိုက်ပေမဲ့ method မကိုက်လို့ mux က 405 ကို ပြန်ပေးတာ နောက်ဆုံး output line မှာ မြင်ရပါတယ်။

  2. One response helperw.WriteHeader(status)

    writeJSON က Content-Type ကို အရင်သတ်မှတ်၊ status ကို ပြီးမှ ရေး၊ body ကို နောက်ဆုံးမှ encode လုပ်ပါတယ်။ Handler တိုင်းက ဒီ helper ကို သုံးလို့ အစီအစဉ် မမှားတော့ပါဘူး။

  3. Decode and validateif err := json.NewDecoder(r.Body).Decode(&in); err != nil || in.Title == "" {

    JSON ပုံစံ မှားတာနဲ့ title အလွတ်ဖြစ်တာ နှစ်ခုလုံးကို 400 နဲ့ ငြင်းပါတယ်။ {"title":""} က JSON အနေနဲ့ မှန်ပေမဲ့ business rule ကို ချိုးဖောက်လို့ ဒုတိယ စစ်ဆေးချက် လိုပါတယ်။

  4. Read the wildcardid, err := strconv.Atoi(r.PathValue("id"))

    PathValue က string ကို ပြန်ပေးလို့ number ပြောင်းရပါတယ်။ /tasks/abc လို ပြောင်းမရတဲ့ ID ကို 400 နဲ့ ဖြေပြီး ပြောင်းလို့ရပေမဲ့ မရှိတဲ့ ID ကိုတော့ 404 နဲ့ ဖြေပါတယ်။

  5. In-process serversrv := httptest.NewServer(mux) // real HTTP server on a local test port

    NewServer က loopback address ပေါ်မှာ server အစစ်ကို ဖွင့်လို့ routing၊ header၊ status အားလုံး production မှာလို အလုပ်လုပ်ပါတယ်။ defer srv.Close() က program ပြီးတဲ့အခါ server ကို ပိတ်ပေးပါတယ်။

You should see
POST /tasks -> 201 {"id":1,"title":"write tests","done":false}
GET /tasks/1 -> 200 {"id":1,"title":"write tests","done":false}
GET /tasks/42 -> 404 {"error":"task not found"}
GET /tasks/abc -> 400 {"error":"id must be a number"}
POST /tasks -> 400 {"error":"title is required"}
DELETE /tasks/1 -> 405 Method Not Allowed

Server အစစ်အဖြစ် run ခြင်းနဲ့ input ကို ကန့်သတ်ခြင်း

httptest က စမ်းသပ်ဖို့ပါ။ တကယ့် server အဖြစ် run တဲ့အခါ mux တူတူကို http.Server ထဲ ထည့်ပြီး timeout တွေ သတ်မှတ်ပါ။ http.ListenAndServe ကို တိုက်ရိုက် သုံးရင် timeout မရှိလို့ နှေးတဲ့ client တွေက connection တွေကို အကြာကြီး ကိုင်ထားနိုင်ပါတယ်။ Body အရွယ်အစားကိုလည်း http.MaxBytesReader နဲ့ ကန့်သတ်ပြီး မမျှော်လင့်တဲ့ field တွေကို DisallowUnknownFields နဲ့ ငြင်းနိုင်ပါတယ်။

go
srv := &http.Server{
    Addr:              ":8080",
    Handler:           mux,
    ReadHeaderTimeout: 5 * time.Second,
    ReadTimeout:       10 * time.Second,
    WriteTimeout:      10 * time.Second,
}
log.Fatal(srv.ListenAndServe())

// inside a handler that accepts a body:
r.Body = http.MaxBytesReader(w, r.Body, 1<<20) // at most 1 MiB
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields() // {"titel": "..."} becomes an error

Handler တွေက တပြိုင်နက် run ပါတယ်

net/http က request တစ်ခုစီကို ကိုယ်ပိုင် goroutine နဲ့ ခေါ်ပါတယ်။ Example ထဲက TaskStore မှာ sync.Mutex ပါတာ ဒါကြောင့်ပါ၊ handler နှစ်ခုက nextID နဲ့ map ကို တစ်ချိန်တည်း ထိနိုင်လို့ပါ။

လက်တွေ့ project တွေမှာ

လက်တွေ့ project တွေမှာ

Go ရဲ့ standard library တစ်ခုတည်းနဲ့ production API တွေ အများကြီး run နေပါတယ်။ Go 1.22 နောက်ပိုင်း ServeMux မှာ method နဲ့ wildcard ပါလာတဲ့အတွက် router library သီးသန့် ထည့်စရာ မလိုတဲ့ project တွေ များလာပါတယ်။ Team တွေက များသောအားဖြင့် ဒီ lesson ထဲက ပုံစံတွေကို အောက်ပါအတိုင်း ပြန်သုံးကြပါတယ်။

  • Error response တိုင်းကို {"error": "..."} ပုံစံ တစ်မျိုးတည်းနဲ့ ပြန်ပြီး frontend က message ကို တစ်နေရာတည်းကနေ ပြသပါတယ်။
  • Handler တွေကို struct (TaskStore လို) ရဲ့ method အဖြစ် ရေးပြီး database connection ဒါမှမဟုတ် logger လို dependency တွေကို struct field ကနေ ထိုးပေးပါတယ်။
  • Handler test တိုင်းက httptest.NewRecorder ဒါမှမဟုတ် httptest.NewServer ကို သုံးလို့ CI မှာ network port ဖွင့်စရာ မလိုပါဘူး။
  • Logging, authentication, panic recovery လို အလုပ်တွေကို http.Handler ကို ဝန်းထားတဲ့ middleware function တွေနဲ့ ထည့်ပါတယ်။
  • Mobile app ဟောင်းတွေ ဆက်အလုပ်လုပ်နိုင်အောင် /v1/tasks လို version ပါတဲ့ path တွေကို သုံးပြီး response shape ကို ပြောင်းချင်တဲ့အခါ /v2 အသစ်တစ်ခု ဖွင့်ပါတယ်။

အမှားများ

HTTP handler တွေမှာ ဖြစ်လေ့ရှိတဲ့ အမှားများ

Error ရေးပြီးနောက် return မေ့ခြင်း

http.Error(w, ...) ဒါမှမဟုတ် writeJSON(w, 400, ...) ကို ခေါ်ပေမဲ့ return မပါရင် handler က ဆက် run ပြီး success body ကိုပါ ထပ်ရေးပါတယ်။ Client က JSON နှစ်ခု ဆက်နေတဲ့ body ကို ရပြီး log ထဲမှာ 'superfluous response.WriteHeader call' warning ပေါ်ပါတယ်။

Header ကို WriteHeader ဒါမှမဟုတ် Write ပြီးမှ သတ်မှတ်ခြင်း

w.WriteHeader(201) ပြီးမှ w.Header().Set("Content-Type", ...) ကို ခေါ်ရင် header က ထွက်သွားပြီးသားမို့ ဘာမှ မပြောင်းတော့ပါဘူး၊ error လည်း မပြပါဘူး။ Header တွေကို အရင်ဆုံး သတ်မှတ်ပါ။

Export မလုပ်ထားတဲ့ field နဲ့ JSON tag မှားခြင်း

type Task struct { title string } ဆိုရင် encoding/json က title ကို မမြင်လို့ response မှာ {} ပဲ ထွက်ပြီး decode မှာလည်း မဖြည့်ပါဘူး။ Field ကို စာလုံးကြီးနဲ့ စပြီး json:"title" tag ထည့်ပါ။ Tag ထဲက စာလုံးပေါင်း မှားရင် field က zero value ပဲ ကျန်လို့ validation က ဖမ်းပေးနိုင်အောင် ထားပါ။

Best Practices

Best practices

  • Header-status-body အစီအစဉ်ကို writeJSON လို helper တစ်ခုထဲ စုထားပါ။
  • Pattern ထဲမှာ method ကို အမြဲ ရေးပါ၊ ဒါမှ မထောက်ပံ့တဲ့ method တွေကို mux က 405 နဲ့ ငြင်းပေးပါတယ်။
  • Server အစစ်မှာ http.Server timeout တွေနဲ့ MaxBytesReader ကို သတ်မှတ်ပါ။
  • Status code တိုင်းအတွက် httptest နဲ့ test case တစ်ခုစီ ရေးပါ၊ error လမ်းကြောင်းတွေ အထူးသဖြင့်ပါ။

Mini challenge

Mini challenge: scoreboard API

ကစားသမား အမှတ်တွေကို စုပေးတဲ့ API လေး တစ်ခု ရေးပါ။ POST /scores က {"player":"ada","points":5} ကို လက်ခံပြီး ကစားသမားရဲ့ စုစုပေါင်းကို တိုးပေးပါတယ်။ GET /scores/{player} က စုစုပေါင်းကို ပြန်ပေးပါတယ်။ Server ကို port မဖွင့်ဘဲ httptest.NewRecorder နဲ့ mux.ServeHTTP ကို တိုက်ရိုက် ခေါ်ပြီး စမ်းပါ။

  • Route နှစ်ခုကို method + wildcard pattern နဲ့ register လုပ်ပါ
  • JSON ပုံစံ မှားတာ ဒါမှမဟုတ် မသိတဲ့ field ပါတာကို 400၊ player အလွတ် ဒါမှမဟုတ် points ≤ 0 ကို 422 နဲ့ ငြင်းပါ
  • မရှိတဲ့ player ကို 404 နဲ့ ဖြေပါ
  • Map ကို mutex နဲ့ ကာကွယ်ပြီး request ခြောက်ခုရဲ့ status နဲ့ body ကို print ထုတ်ပါ
scoreboard.go
package main

import (
    "encoding/json"
    "fmt"
    "net/http"
    "net/http/httptest"
    "strings"
    "sync"
)

type Scoreboard struct {
    mu     sync.Mutex
    points map[string]int
}

type scoreInput struct {
    // TODO: Player and Points fields with json tags
}

func (b *Scoreboard) addScore(w http.ResponseWriter, r *http.Request) {
    // TODO: decode with DisallowUnknownFields, validate, add, respond
}

func (b *Scoreboard) getScore(w http.ResponseWriter, r *http.Request) {
    // TODO: read r.PathValue("player"), answer 200 or 404
}

func main() {
    board := &Scoreboard{points: map[string]int{}}
    mux := http.NewServeMux()
    // TODO: register "POST /scores" and "GET /scores/{player}"

    // TODO: send requests with httptest.NewRecorder + mux.ServeHTTP
    _ = board
    fmt.Println("todo")
}

ရလဒ်: ada ကို 5 နဲ့ 3 ထည့်ပြီးနောက် GET /scores/ada က 200 {"player":"ada","total":8} ပြန်ပါတယ်။ bob က 404၊ points -2 က 422၊ "pts" လို မသိတဲ့ field က 400 ရပါတယ်။

အရိပ်အမြွက် ကြည့်ရန်

rec := httptest.NewRecorder() ပြီးနောက် mux.ServeHTTP(rec, httptest.NewRequest(method, target, strings.NewReader(body))) လို့ ခေါ်ပါ။ ရလဒ်ကို rec.Code နဲ့ rec.Body.String() ကနေ ဖတ်နိုင်ပါတယ်။ Total ကို lock ကိုင်ထားစဉ်မှာပဲ ဖတ်ပါ။

အဖြေ ကြည့်ရန်
scoreboard.go
package main

import (
    "encoding/json"
    "fmt"
    "net/http"
    "net/http/httptest"
    "strings"
    "sync"
)

type Scoreboard struct {
    mu     sync.Mutex
    points map[string]int
}

type scoreInput struct {
    Player string `json:"player"`
    Points int    `json:"points"`
}

func respond(w http.ResponseWriter, status int, v any) {
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(status)
    json.NewEncoder(w).Encode(v)
}

func (b *Scoreboard) addScore(w http.ResponseWriter, r *http.Request) {
    var in scoreInput
    dec := json.NewDecoder(r.Body)
    dec.DisallowUnknownFields()
    if err := dec.Decode(&in); err != nil {
        respond(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON body"})
        return
    }
    if in.Player == "" || in.Points <= 0 {
        respond(w, http.StatusUnprocessableEntity,
            map[string]string{"error": "player and positive points are required"})
        return
    }
    b.mu.Lock()
    b.points[in.Player] += in.Points
    total := b.points[in.Player]
    b.mu.Unlock()
    respond(w, http.StatusOK, map[string]any{"player": in.Player, "total": total})
}

func (b *Scoreboard) getScore(w http.ResponseWriter, r *http.Request) {
    player := r.PathValue("player")
    b.mu.Lock()
    total, ok := b.points[player]
    b.mu.Unlock()
    if !ok {
        respond(w, http.StatusNotFound, map[string]string{"error": "unknown player"})
        return
    }
    respond(w, http.StatusOK, map[string]any{"player": player, "total": total})
}

func main() {
    board := &Scoreboard{points: map[string]int{}}
    mux := http.NewServeMux()
    mux.HandleFunc("POST /scores", board.addScore)
    mux.HandleFunc("GET /scores/{player}", board.getScore)

    send := func(method, target, body string) {
        rec := httptest.NewRecorder()
        mux.ServeHTTP(rec, httptest.NewRequest(method, target, strings.NewReader(body)))
        fmt.Printf("%-4s %-14s %d %s", method, target, rec.Code, rec.Body.String())
    }

    send("POST", "/scores", `{"player":"ada","points":5}`)
    send("POST", "/scores", `{"player":"ada","points":3}`)
    send("GET", "/scores/ada", "")
    send("GET", "/scores/bob", "")
    send("POST", "/scores", `{"player":"bob","points":-2}`)
    send("POST", "/scores", `{"player":"bob","pts":2}`)
}

Quick Quiz 1 / 3

mux.HandleFunc("GET /tasks/{id}", get) ကိုပဲ register လုပ်ထားပါတယ်။ Client က DELETE /tasks/7 ပို့ရင် ဘာဖြစ်မလဲ?

Quick Quiz 2 / 3

Handler တစ်ခုက w.WriteHeader(http.StatusCreated) ပြီးမှ w.Header().Set("Content-Type", "application/json") ကို ခေါ်ပါတယ်။ Client က ဘာ ရမလဲ?

Quick Quiz 3 / 3

Body {"title": "buy milk"} ကို var in struct{ title string } ထဲ Decode လုပ်ပါတယ်။ ရလဒ်က ဘာလဲ?

မှတ်ထားရမယ့် အချက်များ

  • Go 1.22+ ServeMux pattern တွေမှာ method နဲ့ {wildcard} ပါပြီး r.PathValue နဲ့ ဖတ်ပါတယ်။
  • json.NewDecoder နဲ့ decode ပြီးရင် business rule တွေကို ကိုယ်တိုင် စစ်ပြီး error ဆို 4xx ပြန်ကာ return လုပ်ပါ။
  • Response ကို header၊ status၊ body အစီအစဉ်နဲ့ ရေးပါ၊ helper တစ်ခုထဲ ထည့်ထားရင် ပိုလုံခြုံပါတယ်။
  • httptest.NewServer နဲ့ httptest.NewRecorder က API ကို network မလိုဘဲ program ထဲမှာ စမ်းခွင့်ပေးပါတယ်။

Package net/http — Go Packages

နောက်ဆုံးပြင်ဆင်ရက်

Progress ကို ဤ browser (ဤစက်) တွင်သာ သိမ်းထားပါသည်။ အခြားစက်များနှင့် sync မလုပ်ပါ။

ဤသင်ခန်းစာတွင် အမှားတွေ့ပါက အကြောင်းကြားရန်သင့် email app ကို ဤသင်ခန်းစာလိပ်စာ ဖြည့်ပြီးသားဖြင့် ဖွင့်ပေးပါမည် — သင်ကိုယ်တိုင် ပို့မှသာ ပို့မည်ဖြစ်သည်။