HTTP Handler Functions
HTTP handler funksiyalari
Har bir handler ikkita narsa oladi: http.ResponseWriter (javob yozish uchun) va *http.Request (kelgan so'rov haqida ma'lumot). Bu ikkisi bilan ishlashni chuqurroq ko'ramiz.
package main
import (
"fmt"
"net/http"
"net/http/httptest"
)
func infoHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
if r.Method != "GET" {
w.WriteHeader(http.StatusMethodNotAllowed)
fmt.Fprint(w, "faqat GET qabul qilinadi")
return
}
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Metod: %s, Yo'l: %s", r.Method, r.URL.Path)
}
func main() {
req := httptest.NewRequest("GET", "/info", nil)
rec := httptest.NewRecorder()
infoHandler(rec, req)
fmt.Println(rec.Code)
fmt.Println(rec.Body.String())
}w.Header().Set(...) javob sarlavhalarini o'rnatadi — bu `w.WriteHeader` chaqirilishidan oldin bo'lishi shart, chunki status kod yuborilgach sarlavhalarni o'zgartirib bo'lmaydi. w.WriteHeader(kod) status kodni yuboradi (http.StatusOK — 200, http.StatusMethodNotAllowed — 405 kabi tayyor konstantalar bor). r.Method va r.URL.Path — kelgan so'rov haqidagi asosiy ma'lumotlar.
>_ Exercise
Faqat POST metodini qabul qiladigan handler yozing.
- •r.Method "POST" bo'lmasa, 405 status va "faqat POST" matnini qaytaring
- •POST bo'lsa, 201 status va "yaratildi" matnini qaytaring
Stuck? Reveal a hint to help you.
Key Takeaway
Key Takeaway:
Handler ichida r.Methodni tekshirish, mos status kod bilan javob berish — HTTP serverlarning eng asosiy naqshlaridan biri.
NEXT UP
Routing and Path Parameters
$ go run main.go
Kodingizni ishga tushiring