Making HTTP Request in Go
Go, also known as Golang, is a statically typed, compiled language designed at Google. One of its many strengths is its standard library, which includes a robust set of tools for making HTTP requests. This article will guide you through making HTTP requests using Go's net/http
package.
The net/http
Package
The net/http
package provides functionalities for building HTTP clients and servers. To make an HTTP request, we primarily use the http.Get
, http.Post
, http.PostForm
, http.Head
, and http.NewRequest
functions.
Here's a simple example of making a GET request:
package main
import (
"io/ioutil"
"log"
"net/http"
)
func main() {
resp, err := http.Get("https://jsonplaceholder.typicode.com/posts")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
log.Println(string(body))
}
In this example, http.Get
makes a GET request to https://jsonplaceholder.typicode.com/posts
. The response (resp
) includes both the server's response to the HTTP request and the response body (resp.Body
), which is a readable stream.
Remember to close the response body when you're done with it. Not doing so can result in resource leaks in long-running programs.
Making POST Requests
Making a POST request is similar to making a GET request. Here's an example:
package main
import (
"strings"
"log"
"net/http"
)
func main() {
resp, err := http.Post(
"https://jsonplaceholder.typicode.com/posts",
"application/x-www-form-urlencoded",
strings.NewReader("name=test"),
)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
}
In this example, http.Post
sends a POST request with name=test
as the body.
Conclusion
The net/http
package in Go provides a powerful interface for making HTTP requests. With it, you can send GET, POST, and other types of HTTP requests. Remember to handle errors and close response bodies properly to avoid resource leaks.
- For more information, refer to the official Go documentation:
- Go at Google: Language Design in the Service of Software Engineering
- net/http - The Go Programming Language
- Making HTTP requests in Go
- Don't defer Close() on writable files
- Go by Example: HTTP Clients.