Client with net/http
- Go course
- Intermediate
- Lesson 65/80
- 4 min
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.
Practice 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.
Starter code
package main
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"time"
)
func main() {
// buraya yaz
}Sample 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))
}Expected output
200 pong
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 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 Correct answer
- A nil response and an error
Explanation: Do returns an error only on network/protocol failures; 4xx and 5xx are valid HTTP responses.
2 Close the body
resp, err := istemci.Do(req)
if err != nil { return err }
____ resp.Body.Close()
resp, err := istemci.Do(req)
if err != nil { return err }
defer resp.Body.Close()
Explanation: defer resp.Body.Close() makes sure the connection returns to the pool.
3 Client step
| Term | Meaning |
|---|---|
NewRequestWithContext |
Request and cancellation |
req.Header.Set |
Adds a header |
client.Do |
Sends it |
resp.StatusCode |
Result code |