Sling Academy
Home/Golang/How to send POST requests with body and headers in Go

How to send POST requests with body and headers in Go

Last updated: November 27, 2024

Sending HTTP POST requests is a common task when building applications that need to communicate over the Internet. In Go, you can use the net/http package to achieve this. This article will guide you through the process of sending POST requests with both a body and custom headers.

Prerequisites

Before you begin, ensure you have Go installed on your machine. You can download it from the official Go website if it is not already installed. Additionally, you should have a basic understanding of Go syntax and how to run Go programs.

Using net/http to Send POST Requests

The net/http package is included in the Go standard library and provides the functionality needed to send HTTP requests.

1. Import the Necessary Packages

Start by creating a new Go file and import the required packages:

package main

import (
    "bytes"
    "fmt"
    "net/http"
    "io/ioutil"
    "log"
)

2. Create the POST Request

Next, we will create a sample POST request to demonstrate the process. First, set up the URL and the request body:

func main() {
    url := "https://example.com/api"
    var jsonStr = []byte(`{"key":"value"}`)

    req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
    if err != nil {
        log.Fatalf("Error creating request: %v", err)
    }

In the above code, we're setting up a POST request to https://example.com/api with a JSON body containing a simple key-value pair.

3. Set Request Headers

After creating the request, you can set custom headers that the server might require. Here, we'll set the Content-Type to application/json to indicate that the data is in JSON format:

req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer ")

As an example, we've set an Authorization header, which is common when working with APIs that require authentication tokens.

4. Send the Request

After setting the headers, you can send the request using an HTTP client:

client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
    log.Fatalf("Error sending request: %v", err)
}
defer resp.Body.Close()

5. Read the Response

Finally, read and process the response from the server:

body, err := ioutil.ReadAll(resp.Body)
if err != nil {
    log.Fatalf("Error reading response body: %v", err)
}
fmt.Println("Response Status:", resp.Status)
fmt.Println("Response Body:", string(body))

Conclusion

That's it! You have sent a POST request with a body and headers in Go using the net/http package. You can now integrate similar logic into your applications whenever you need to send HTTP requests.

Remember to replace example.com/api and the request body with your actual endpoint and data. Adjust headers as necessary based on the requirements of the API you are interacting with.

Next Article: How to extract user IP address and user agent in Go server

Previous Article: How to send GET requests with params in Go

Series: Networking and Server

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant