HTTP Client in Go
Start with HTTP Client in Go
In this lesson, explore http client in go through one small Go program, and connect its output to the language rules behind it.
What you’ll learn
- Explain the main purpose of http client in go.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
An http.Client sends outbound requests and manages connections. Reuse clients rather than constructing one per request, set timeouts, and close response bodies when finished.
The example uses a fake transport so the program remains self-contained without an external network or local listener.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import (
"fmt"
"io"
"net/http"
"strings"
"time"
)
type transportFunc func(*http.Request) (*http.Response, error)
func (f transportFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
func main() {
client := &http.Client{Timeout: time.Second, Transport: transportFunc(func(r *http.Request) (*http.Response, error) {
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader("pong")), Header: make(http.Header), Request: r}, nil
})}
resp, err := client.Get("https://example.invalid/ping")
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
panic(err)
}
fmt.Println(resp.StatusCode, string(body))
}
Output
200 pongTrace what the program does
The custom transport returns a fixed HTTP response without making a network request. The client reads and closes its body, then prints 200 pong.
Avoid common mistakes
- Always close a successful response body.
- For real calls, propagate request context and set deadlines; never assume a remote server responds.
Try it yourself
Use client.NewRequestWithContext and check a non-200 status before reading a response.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced HTTP Client in Go in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.