CodeBlanks Logo Icon CodeBlanks

http.Get

http.Get ile basit GET isteği yapmayı öğrenirsin.

http.Get

Basit durumlar için http.Get(url) kısa yoldur; arka planda http.DefaultClient.Get çağırır. Yanıtın durum kodunu kontrol etmek ve gövdeyi kapatmak yine senin görevindir:

resp, err := http.Get(url)
if err != nil { return err }
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
    return fmt.Errorf("beklenmeyen durum: %s", resp.Status)
}
var urunler []Urun
return json.NewDecoder(resp.Body).Decode(&urunler)

POST ve form

JSON göndermek için http.Post ya da NewRequest kullanılır; form verisi için http.PostForm:

govde, _ := json.Marshal(YeniUrun{Ad: "Kalem"})
resp, err := http.Post(url, "application/json", bytes.NewReader(govde))

resp, err = http.PostForm(url, url.Values{"ad": {"Kalem"}})

Her durumda yanıt gövdesi kapatılır ve durum kodu kontrol edilir.

Uygulama JSON istemcisi

Test sunucusu [{"ad":"Kalem"},{"ad":"Defter"}] döndürsün. http.Get(srv.URL) ile al, durum kodunu kontrol et, gövdeyi json.NewDecoder ile []struct{ Ad string `json:"ad"` } dilimine çöz ve eleman sayısını yazdır.

Başlangıç kodu

main.go
package main

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

func main() {
    // buraya yaz
}

Örnek çözüm

main.go
package main

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

func main() {
    srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/json")
        fmt.Fprint(w, `[{"ad":"Kalem"},{"ad":"Defter"}]`)
    }))
    defer srv.Close()

    resp, err := http.Get(srv.URL)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer resp.Body.Close()
    if resp.StatusCode != http.StatusOK {
        fmt.Println(resp.Status)
        return
    }
    var urunler []struct {
        Ad string `json:"ad"`
    }
    if err := json.NewDecoder(resp.Body).Decode(&urunler); err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(len(urunler))
}

Beklenen çıktı

2

Soru ve cevaplar

Dersin sorularını cevaplarıyla birlikte inceleyebilirsin. Kendini denemek istersen dersi interaktif olarak çöz.

1 <code>resp.Status</code> ile <code>resp.StatusCode</code> farkı nedir?

  • StatusCode başlıklardır
  • Status metindir ("200 OK"), StatusCode sayıdır (200) Doğru cevap
  • Aynı şeydir
  • Status yalnızca hatalarda dolar

Açıklama: Karşılaştırma için StatusCode, log ve hata mesajı için Status kullanılır.

2 Durumu kontrol et

Soru
if resp.____ != http.StatusOK {
    return fmt.Errorf("durum: %s", resp.Status)
}
Cevap
if resp.StatusCode != http.StatusOK {
    return fmt.Errorf("durum: %s", resp.Status)
}

Açıklama: StatusCode yanıtın sayısal HTTP durum kodudur.

3 Fonksiyon ve yöntem

Kavram Anlamı
http.Get GET
http.Post POST + gövde
http.PostForm POST + form
http.Head Yalnızca başlıklar

Orta seviye bölümündeki tüm dersler