How do you send an HTTP POST request with an HTTP client in Go?
Example
package main
import (
"bytes"
"net/http"
)
func main() {
url := "http://example.com/api"
jsonStr := []byte(`{"name":"John","age":30,"city":"New York"}`)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
// Handle response
}
In this example, we first create a NewRequest object with the HTTP method set to POST, the URL set to the API endpoint, and the request body set to the JSON data we want to send.
We also set the Content-Type header to application/json to indicate that we are sending JSON data.
Then, we create an HTTP client using the http.Client struct and call its Do method with the req object we created earlier. This sends the HTTP request to the server and returns an HTTP response object.
Finally, we handle the response by reading the response body and handling any errors that occur.
Example
package main
import (
"bytes"
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.POST("/api", func(c *gin.Context) {
url := "http://example.com/api"
jsonStr := []byte(`{"name":"John","age":30,"city":"New York"}`)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
defer resp.Body.Close()
// Handle response
c.JSON(http.StatusOK, gin.H{
"message": "Request sent successfully",
})
})
router.Run(":8080")
}
In this example, we create a POST route /api using the gin framework's POST method. Inside the route handler, we create an http.NewRequest object with the HTTP method set to POST, the URL set to the API endpoint, and the request body set to the JSON data we want to send.
We also set the Content-Type header to application/json to indicate that we are sending JSON data.
Then, we create an HTTP client using the http.Client struct and call its Do method with the req object we created earlier. This sends the HTTP request to the server and returns an HTTP response object.
Finally, we handle the response by reading the response body and handling any errors that occur. In this example, we return a JSON response with an error message if an error occurs, or a success message if the request is sent successfully.
Example
package controllers
import (
"bytes"
"net/http"
"github.com/astaxie/beego"
)
type ApiController struct {
beego.Controller
}
func (c *ApiController) Post() {
url := "http://example.com/api"
jsonStr := []byte(`{"name":"John","age":30,"city":"New York"}`)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
c.Abort("500")
}
defer resp.Body.Close()
// Handle response
c.Data["json"] = map[string]string{"message": "Request sent successfully"}
c.ServeJSON()
}
In this example, we create a controller ApiController with a Post method. Inside the Post method, we create an http.NewRequest object with the HTTP method set to POST, the URL set to the API endpoint, and the request body set to the JSON data we want to send.
We also set the Content-Type header to application/json to indicate that we are sending JSON data.
Then, we create an HTTP client using the http.Client struct and call its Do method with the req object we created earlier. This sends the HTTP request to the server and returns an HTTP response object.
Finally, we handle the response by reading the response body and handling any errors that occur. In this example, we return a JSON response with a success message if the request is sent successfully. If an error occurs, we abort the request and return a 500 status code.
To return the JSON response, we set the c.Data["json"] variable to a map containing the response data and call c.ServeJSON(). This sets the response header to application/json and writes the response body in JSON format.