How To Make HTTP Requests in Go?
An HTTP request is a message sent by a client (such as a web browser) to a server to request specific information or resources. The request typically includes the HTTP method (such as GET or POST), the URL of the resource being requested, and any necessary headers or data. The server then sends a response back to the client, which can include the requested information, an error message, or a redirect to another resource.
Using net/http
In Go, you can use the built-in net/http package to make HTTP requests. Here is an example of how to make a GET request to a URL:
Example
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
resp, err := http.Get("https://www.example.com")
if err != nil {
fmt.Println("Error:", err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println(string(body))
}
POST Request Example
You can also use the http.NewRequest() function to create a new request with a specific method (e.g. POST, PUT, etc.) and set headers. Here is an example of how to make a POST request with a JSON payload:
Example
package main
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
)
func main() {
jsonData := []byte(`{"name":"John Doe"}`)
req, err := http.NewRequest("POST", "https://www.example.com/post", bytes.NewBuffer(jsonData))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error:", err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("response Status:", resp.Status)
fmt.Println("response Headers:", resp.Header)
fmt.Println("response Body:", string(body))
}
GET Request Example
You can also use the http.NewRequest() function to create a new request and the http.Client.Do() function to send it:
Example
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
req, err := http.NewRequest("GET", "https://www.example.com", nil)
if err != nil {
fmt.Println(err)
return
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(body))
}
Additionally, you can also use third-party packages like
golang.org/x/net/context and
github.com/google/go-querystring to make your HTTP request more powerful.
Most Helpful This Week
Multiple-value <function> in single-value context error in Golang
Golang program to print all Permutations of a given string
Exploring Blockchain: Top 15 Real-World Use Cases in 2024
5 Must-Know Blockchain Trends for 2024 and Beyond
Missing return at end of function error in Golang
GO Program to Find LCM and GCD of given two numbers
Most Helpful This Week
How to check if a string contains a white space in Golang?How to use a mutex to define critical sections of code and fix race conditions?Find element in a slice and move it to first position?Select single argument from all arguments of variadic functionReplace any non-alphanumeric character sequences with a dash using RegexRegular expression to validate email addressConvert Int data type to Int16 Int32 Int64Strip all white spaces, tabs, newlines from a stringHow to use for and foreach loop?Golang Get current Date and Time in EST, UTC and MST?