CodeBlanks Logo Icon CodeBlanks

http.Get

Learn to make a simple GET request with http.Get.

http.Get

For simple cases http.Get(url) is the shortcut; it calls http.DefaultClient.Get underneath. Checking the status code and closing the body are still your job:

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 and forms

To send JSON use http.Post or NewRequest; for form data, 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"}})

In every case the response body is closed and the status code checked.

Practice JSON client

Let the test server return [{"ad":"Kalem"},{"ad":"Defter"}]. Fetch it with http.Get(srv.URL), check the status code, decode the body with json.NewDecoder into a []struct{ Ad string `json:"ad"` } slice and print the number of items.

Starter code

main.go
package main

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

func main() {
    // buraya yaz
}

Sample solution

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))
}

Expected output

2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the difference between <code>resp.Status</code> and <code>resp.StatusCode</code>?

  • StatusCode is the headers
  • Status is text ("200 OK"), StatusCode is a number (200) Correct answer
  • They are the same
  • Status is set only on errors

Explanation: Use StatusCode for comparisons and Status for logs and error messages.

2 Check the status

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

Explanation: StatusCode is the response's numeric HTTP status code.

3 Function and method

Term Meaning
http.Get GET
http.Post POST + body
http.PostForm POST + form
http.Head Headers only

All lessons in Intermediate