Go: uploading files via HTTP

Go: uploading files via HTTP

In this article, we'll explore how to implement file upload in Go using the standard "net/http" package.

Go (or Golang) is an open-source programming language created by Google, known for its efficiency and ease of use. It is particularly suitable for developing web applications, including handling file uploads via HTTP. In this article, well explore how to implement file upload in Go using the standard "net/http" package.

To handle file uploads, you need to create an HTTP handler for the endpoint where the files will be sent. Lets start by creating a file called "main.go" and define the handler:


package main

import (
    "fmt"
    "net/http"
)

func uploadHandler(w http.ResponseWriter, r *http.Request) {
    if r.Method != http.MethodPost {
        http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
        return
    }

    file, header, err := r.FormFile("file")
    if err != nil {
        http.Error(w, "Failed to read the file", http.StatusInternalServerError)
        return
    }
    defer file.Close()

    // Puoi ora utilizzare 'file' per accedere al contenuto del file caricato.
    // Ad esempio, puoi copiare il file su disco o elaborarlo in qualche altro modo.

    fmt.Fprintf(w, "File '%s' caricato correttamente.\n", header.Filename)
}

func main() {
    http.HandleFunc("/upload", uploadHandler)

    // Ascolta sulla porta 8080 e avvia il server.
    fmt.Println("Server in ascolto su http://localhost:8080")
    http.ListenAndServe(":8080", nil)
}

In this example, we have created a handler called uploadHandler which will be called when a POST request is made to the "/upload" endpoint. If the request is not a POST type, we will respond with a "Method not allowed" error. Next, well use r.FormFile("file") to access the uploaded file and get information about it, such as the file name. You can then proceed to process the file as you wish.

To test the upload endpoint, lets create a simple HTML client. Create a file called "index.html" with the following content:


<!DOCTYPE html>
<html>
<head>
    <title>Carica un file</title>
</head>
<body>
    <h2>Carica un file</h2>
    <form action="http://localhost:8080/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="file" id="file">
        <input type="submit" value="Carica">
    </form>
</body>
</html>

Youve now completed implementing both the Go server and the HTML client. To test the file upload, start the Go server by running the command:

go run main.go

After starting the server, open the "index.html" file in your browser and select a file via the "Upload" button. Once the file is sent, the Go server will receive the request, read the file and reply with a message indicating the name of the uploaded file.