How do you send an HTTP POST request with an HTTP client in Go?

An HTTP POST request is a method of sending data to a server using the HTTP protocol. In a POST request, data is sent in the message body of the request, rather than in the URL, as is the case with HTTP GET requests. The POST method is often used for submitting data to a web server, such as submitting a form or uploading a file. The data sent in a POST request can be in various formats such as form data, JSON, XML, etc., depending on the content type of the request. The message body of a POST request can contain any type of data, such as text, binary, or multimedia content. The server receiving the POST request can process the data and respond with an HTTP status code and a response message, which may contain data in the response body.
HTTP POST request
In Go, you can send an HTTP POST request with an HTTP client using the net/http package. Here is an example of how to do it:

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.


HTTP POST using GIN framework
In Go Gin, you can send an HTTP POST request with an HTTP client using the net/http package and the gin framework's context object. Here's an example of how to do it:

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.


HTTP POST using Beego
In Go Beego, you can send an HTTP POST request with an HTTP client using the net/http package and the beego framework's Controller object. Here's an example of how to do it:

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.


Most Helpful This Week