Go
Client with net/http
Learn to make HTTP requests with http.Client.
HTTP clients with net/http
net/http contains both a client and a server. On the client side there are three steps: build the request, send it, handle the response and close the body.
req, err := http.NewRequestWithContext(ctx, "GET", "https://api.ornek.com/urunler", nil)
if err != nil { return err }
req.Header.Set("Accept", "application/json")
resp, err := istemci.Do(req)
if err != nil { return err }
defer resp.Body.Close()
http.DefaultClient has no timeout; in production create your own client such as &http.Client{Timeout: 10 * time.Second}.
Close the body
If resp.Body isn't closed, the TCP connection doesn't return to the pool and connections run out over time. Closing the body without reading it can also prevent reuse; reading it fully or draining it with io.Copy(io.Discard, resp.Body) is best. For large responses, limit reading with io.LimitReader.
Exercise Request to a test server
Start a server that writes "pong" with httptest.NewServer (defer srv.Close()). Send a GET to srv.URL with an http.Client that has a timeout, read the body with io.ReadAll, and print the status code and body.
Show example solution
package main
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"time"
)
func main() {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "pong")
}))
defer srv.Close()
istemci := &http.Client{Timeout: 5 * time.Second}
resp, err := istemci.Get(srv.URL)
if err != nil {
fmt.Println(err)
return
}
defer resp.Body.Close()
b, _ := io.ReadAll(resp.Body)
fmt.Println(resp.StatusCode, string(b))
}
Test yourself
-
When the server returns 404, what does <code>client.Do</code> return?
- A panic
- An empty body and an error
- A response and a nil error; you must check resp.StatusCode
- A nil response and an error
Show answer
A response and a nil error; you must check resp.StatusCode — Do returns an error only on network/protocol failures; 4xx and 5xx are valid HTTP responses.
-
Close the body
resp, err := istemci.Do(req)
if err != nil { return err }
____ resp.Body.Close()
Show answer
resp, err := istemci.Do(req)
if err != nil { return err }
defer resp.Body.Close()
-
Client step
- NewRequestWithContext
- Request and cancellation
- req.Header.Set
- Adds a header
- client.Do
- Sends it
- resp.StatusCode
- Result code
Next lesson: http.Get