Shorten Endpoint
Qisqartirish endpoint'i
Endi qurgan ikkita qismni (Store va CodeGenerator) birlashtirib, tashqi dunyo bilan "gaplashadigan" birinchi HTTP endpoint'ni yasaymiz: foydalanuvchi uzun havolani yuborsa, server unga qisqa kodni qaytarishi kerak.
package main
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
)
type ShortenRequest struct {
URL string `json:"url"`
}
type ShortenResponse struct {
Code string `json:"code"`
}
func makeShortenHandler(gen *CodeGenerator, store *Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req ShortenRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
code := gen.Next()
store.Save(&URLRecord{Code: code, OriginalURL: req.URL})
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(ShortenResponse{Code: code})
}
}
func main() {
gen := &CodeGenerator{}
store := NewStore()
handler := makeShortenHandler(gen, store)
body := `{"url":"https://godasturchi.uz"}`
req := httptest.NewRequest("POST", "/shorten", strings.NewReader(body))
rec := httptest.NewRecorder()
handler(rec, req)
fmt.Println(rec.Body.String())
}makeShortenHandler(gen, store) — "HTTP Service Communication" darsida ko'rgan "kerakli narsalarni parametr sifatida berish" naqshi: handler o'zi qayerdan CodeGenerator yoki Store olishini "bilmaydi", ular unga TASHQARIDAN beriladi. Bu — handler'ni testda (haqiqiy production server ishga tushirmasdan) sinash imkonini beradi, aynan shu misoldagi kabi.
json.NewDecoder(r.Body).Decode(&req) — "JSON Encoding" darsida ko'rgan so'rov tanasini ("body") to'g'ridan-to'g'ri Go struct'iga aylantirish usuli. Xato bo'lsa (masalan noto'g'ri JSON), http.StatusBadRequest (400) qaytariladi — bu "RESTful API Design" darsida ko'rgan "mos status kodni qaytarish" tamoyili.
>_ Exercise
Bo'sh URL yuborilganda xato qaytaruvchi tekshiruv qo'shing.
- •makeShortenHandler ichida, req.URL bo'sh ("") bo'lsa, http.StatusBadRequest qaytaring va funksiyadan chiqing
- •{"url":""} tanasi bilan so'rov yuborib, rec.Code qiymatini chop eting
Stuck? Reveal a hint to help you.
Key Takeaway
Key Takeaway:
Shorten endpoint — kiruvchi JSON so'rovni tekshiradi, noto'g'ri ma'lumot uchun mos xato kodini qaytaradi, va faqat to'g'ri ma'lumot uchun yangi qisqa kod yaratib, uni saqlaydi.
NEXT UP
Redirect Endpoint
$ go run main.go
Kodingizni ishga tushiring