Golang Send File – Upload with POST request

This Golang Send File tutorial covers, how to upload files to an endpoint using POST requests. If you’re looking to manage file uploads on the server side, refer to the Golang file upload post. However, if your aim is to send a file to an endpoint, please proceed with this post.

File upload functionality is an essential component of many web applications. In Golang, uploading a file to an endpoint using a POST request can be efficiently implemented using the standard “net/http” package. This article explores how Golang developers can send single or multiple files to a server endpoint using POST requests with comprehensive examples and explanations. The language is friendly and tailored to developers looking to enhance their back-end skills.

Table of Contents

  1. Prerequisites
  2. Uploading a Single File
  3. Uploading Multiple Files
  4. Error Handling in File Upload
  5. Sample Output
  6. Conclusive Summary
  7. References

Prerequisites

Before diving into the code, ensure you have a Go environment set up and that you are familiar with basic Go syntax. This article also assumes you have a basic understanding of HTTP and the concept of file uploading in web applications.

 

Uploading a Single File

To upload a file to an HTTP server endpoint, a multipart/form-data POST request is typically used. Below is a Golang function to send a single file, along with an explanation of its components.

func UploadFile(url string, paramName string, filePath string) error {
  file, err := os.Open(filePath)
  if err != nil {
    return err
  }
  defer file.Close()

  body := &bytes.Buffer{}
  writer := multipart.NewWriter(body)
  part, err := writer.CreateFormFile(paramName, filepath.Base(filePath))
  if err != nil {
    return err
  }
  _, err = io.Copy(part, file)

  err = writer.Close()
  if err != nil {
    return err
  }

  request, err := http.NewRequest("POST", url, body)
  request.Header.Add("Content-Type", writer.FormDataContentType())
  client := &http.Client{}
  response, err := client.Do(request)

  if err != nil {
    return err
  }
  defer response.Body.Close()

  // Handle the server response...
  return nil
}

In this example, we define a function UploadFile that takes the URL of the endpoint, the form parameter name, and the path to the file to be uploaded. It uses the multipart package to create a form file within the request body. Then it copies the file content into the form file part. After constructing the request with the proper headers, it is sent using a new instance of http.Client.

 

Uploading Multiple Files

Uploading multiple files at once is a similar process. The following Golang function sends multiple files in a single POST request.

func UploadMultipleFiles(url string, paramName string, filePaths []string) error {
  body := &bytes.Buffer{}
  writer := multipart.NewWriter(body)

  for _, filePath := range filePaths {
    file, err := os.Open(filePath)
    if err != nil {
      return err
    }
    defer file.Close()

    part, err := writer.CreateFormFile(paramName, filepath.Base(filePath))
    if err != nil {
      return err
    }
    _, err = io.Copy(part, file)

    if err != nil {
      return err
    }
  }

  err := writer.Close()
  if err != nil {
    return err
  }

  request, err := http.NewRequest("POST", url, body)
  request.Header.Add("Content-Type", writer.FormDataContentType())
  client := &http.Client{}
  response, err := client.Do(request)

  if err != nil {
    return err
  }
  defer response.Body.Close()

  // Handle the server response...
  return nil
}

The UploadMultipleFiles function loops through a slice of file paths, each time opening the file and adding it to the multipart writer. Once all files are added, the multipart writer is closed, and the request is constructed and sent in the same manner as in the single file upload example.

Error Handling in File Upload

When uploading files, various errors can occur such as file not found, network issues, or server errors. It is important to include error handling in the functions. In the provided examples, error checking is done with each file operation and network call, ensuring immediate error reporting.

 

Sample Output

After executing the UploadFile or UploadMultipleFiles function, server responses will vary based on your specific endpoint logic. However, we expect a successful HTTP status code (e.g., 200 OK) on successful upload.

  Output:
  HTTP/1.1 200 OK
  Content-Type: text/plain; charset=utf-8
  ...

Conclusive Summary

In this tutorial, you’ve learned how to upload files to an endpoint in Golang using multipart/form-data POST requests. We’ve provided examples for both single and multiple file uploads and highlighted the importance of handling potential errors that could arise during the file upload process.

References