HTTP Client in Go
Go: HTTP Client
The Go standard library provides the
net/http
package for makingHTTP
requests. Here's an example of how to use it to make a simpleGET
request:
package main
import (
"fmt"
"net/http"
)
func main() {
resp, err := http.Get("https://jsonplaceholder.typicode.com/todos/1")
if err != nil {
fmt.Println("Error:", err)
return
}
defer resp.Body.Close()
fmt.Println("Response status:", resp.Status)
}
This code sends a GET request to the specified URL and prints the response status. The http.Get
function returns a response object and an error, which we check for and handle accordingly. We also use the defer keyword to ensure that the response body is closed after we're finished using it.
How to add headers to your request in Go?
You can also add headers to your request by creating a http.Header
object and setting values on it:
package main
import (
"fmt"
"net/http"
)
func main() {
client := &http.Client{}
req, err := http.NewRequest("GET", "https://jsonplaceholder.typicode.com/todos/1", nil)
if err != nil {
fmt.Println("Error:", err)
return
}
req.Header.Set("User-Agent", "my-awesome-client")
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error:", err)
return
}
defer resp.Body.Close()
fmt.Println("Response status:", resp.Status)
}
This code creates a new http.Request object and sets the User-Agent header to a custom value. It then uses an http.Client object to send the request and get the response.
I hope that helps you get started with making HTTP requests in Go! Let me know if you have any more questions.
Previous Article
Next Article
Golang Tutorials
- Hello World
- Operators in Go
- Declarations in Go
- Values in Go
- Variables in Go
- For in Go
- If/Else in Go
- Switch in Go
- Arrays in Go
- Slices in Go
- Maps in Go
- Range in Go
- Functions in Go
- Closures in Go
- Recursion in Go
- Pointers in Go
- Strings and Runes in Go
- Structs in Go
- Methods in Go
- Interfaces in Go
- Generics in Go
- Errors in Go
- Goroutines in Go
- Channels in Go
- Select in Go
- Timeouts in Go
- Timers in Go
- Worker Pools in Go
- WaitGroups in Go
- Mutexes in Go
- Sorting in Go
- Panic in Go
- Defer in Go
- Recover in Go
- JSON in Go
- XML in Go
- Time in Go
- Epoch in Go
- Time Formatting in Go
- Random Numbers in Go
- Number Parsing in Go
- URL Parsing in Go
- SHA256 Hashes in Go
- Base64 Encoding in Go
- Reading Files in Go
- Writing Files in Go
- File Paths in Go
- Directories in Go
- Testing and Benchmarking in Go
- Command-Line Arguments in Go
- Command-Line Flags in Go
- Command-Line Subcommands in Go
- Environment Variables in Go
- HTTP Client in Go
- HTTP Server in Go
- Context in Go
- Signals in Go