Go
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.
Exercise 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.
Show example solution
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))
}
Test yourself
-
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)
- They are the same
- Status is set only on errors
Show answer
Status is text ("200 OK"), StatusCode is a number (200) — Use StatusCode for comparisons and Status for logs and error messages.
-
Check the status
if resp.____ != http.StatusOK {
return fmt.Errorf("durum: %s", resp.Status)
}
Show answer
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("durum: %s", resp.Status)
}
-
Function and method
- http.Get
- GET
- http.Post
- POST + body
- http.PostForm
- POST + form
- http.Head
- Headers only
Next lesson: http.Handler