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
How to print string with double quote in Go?How to handle HTTP Get response?How to read names of all files and folders in current directory?Various examples of printing and formatting in GolangRuntime package variablesHow to declare empty Map in Go?How pointer & and * and ** works in Golang?How to import structs from another package in Go?Golang Read Write Create and Delete text fileHow to use for and foreach loop?