The Go HTTP client lets your program call other web services, such as a payment API or a weather service. In this post, you will send GET and POST requests, decode JSON and add headers. You will also set timeouts and handle errors safely.
So far, you built servers in the Go REST API tutorial. Now your code becomes the caller. We also decode responses with the tools from Go JSON encoding and decoding.
What Is the Go HTTP Client?
The net/http package includes both a server and a client. In short, the client sends a request and waits for the reply. Then it gives you an *http.Response with a status, headers and a body.
Think of ordering food by phone. First, you dial the number and say what you want. Then you wait, and finally the restaurant answers with your order or an apology. Similarly, a request goes out, and a response comes back.
Always Create a Client with a Timeout
client := &http.Client{Timeout: 2 * time.Second}
The quick helper http.Get uses the default client, which has no timeout at all. Therefore, one slow server could make your program wait forever. So create your own Go HTTP client once and set a timeout. Also reuse it everywhere, because it keeps connections open for speed.
Sending a GET Request with the Go HTTP Client
resp, err := client.Get(baseURL + "/books/1")
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("unexpected status: %s", resp.Status)
}
var book Book
if err := json.NewDecoder(resp.Body).Decode(&book); err != nil {
return err
}
fmt.Printf("%+v\n", book) // {ID:1 Title:Go Basics Author:Asha}
There are three checks here, and each one matters. First, err reports network problems. Next, the status code reports problems on the server side. Finally, the decoder reports bad JSON.
The diagram below shows the full round trip.

The client sends a request, the server replies with a status and a body, and your code checks the error, the status and the JSON in that order.
A 404 Is Not an Error
resp, _ := client.Get(baseURL + "/missing")
resp.Body.Close()
fmt.Println(resp.StatusCode, resp.Status) // 404 404 Not Found
This surprises many beginners. The Go HTTP client only returns an error when the request itself fails, such as a refused connection. A 404 or 500 is still a valid answer, so you must check StatusCode yourself.
Sending JSON with POST
body, _ := json.Marshal(Book{Title: "Go Testing", Author: "Ravi"})
resp, err := client.Post(baseURL+"/books", "application/json", bytes.NewReader(body))
if err != nil {
return err
}
defer resp.Body.Close()
var created Book
json.NewDecoder(resp.Body).Decode(&created)
fmt.Println(resp.Status, created.ID, created.Title) // 201 Created 2 Go Testing
Post takes the URL, the content type and a body reader. Here bytes.NewReader turns our JSON bytes into that reader. Also, the server answered with 201 Created, which is the usual status for a new record. So in real code, check for http.StatusCreated rather than 200 after a POST.
Custom Headers and Context with NewRequest
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "GET", baseURL+"/auth", nil)
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer abc123")
resp, err := client.Do(req)
For anything beyond a simple call, build the request yourself. Then you can add headers such as an API token and attach a context. As a result, the call stops early when the user cancels, just like in Go context for beginners.
Go HTTP Client Errors You Will See
Get "http://127.0.0.1:PORT/slow": context deadline exceeded (Client.Timeout exceeded while awaiting headers)
Get "http://127.0.0.1:PORT/slow": context deadline exceeded
Get "http://localhost:1/x": dial tcp 127.0.0.1:1: connect: connection refused
The first line comes from the client timeout, while the second comes from a context deadline. Meanwhile, the third means nothing is listening on that port. We produced all three against a local test server.
Common Mistakes with the Go HTTP Client
| Problem you see | Why it happens | How to fix it |
|---|---|---|
| Program hangs on a slow API | Because http.Get has no timeout. | So create a client with Timeout. |
| Too many open connections | Because the body was never closed. | So always defer resp.Body.Close(). |
| 404 treated as success | Because only err was checked. | So check resp.StatusCode too. |
| Nil pointer panic on resp | Because resp was used when err was not nil. | So return early on any error. |
API client questions are popular in backend interviews. So practise with my Go interview questions and answers.
Official Resources
These pages come straight from the Go team, so they stay accurate and up to date.
Quick Recap
- The Go HTTP client lives in
net/httpnext to the server. - Create one client with a timeout and reuse it.
- Check the error, then the status code, then decode the body.
- Always close the response body with
defer. - Use
NewRequestWithContextfor headers and cancellation.
What’s Next?
Your code can now talk to other services. Next, we will test that code without calling the real services by using interfaces and mocks.
Next lesson: Go Mocking with Interfaces for Unit Tests


