create a http server and read the request body as multipart form data in go

To create an HTTP server and read the request body as multipart form data in Go, you can use the built-in net/http and mime/multipart packages. Here's an example code snippet that demonstrates how to do this:

main.go
package main

import (
    "fmt"
    "log"
    "mime/multipart"
    "net/http"
)

func main() {
    http.HandleFunc("/upload", func(w http.ResponseWriter, r *http.Request) {
        // Parse the multipart form data from the request body
        err := r.ParseMultipartForm(32 << 20) // 32 MB is the maximum memory that ParseMultipartForm will allocate
        if err != nil {
            http.Error(w, err.Error(), http.StatusBadRequest)
            return
        }

        // Get the file headers from the request
        fileHeaders := r.MultipartForm.File["my-file"]

        // Loop through all the files and do something with them
        for _, fileHeader := range fileHeaders {
            // Open the uploaded file
            file, err := fileHeader.Open()
            if err != nil {
                http.Error(w, err.Error(), http.StatusInternalServerError)
                return
            }
            defer file.Close()

            // Print a basic summary of the file
            fmt.Printf("Received file: %s (%d bytes)\n", fileHeader.Filename, fileHeader.Size)
        }

        // Send a response to the client
        w.WriteHeader(http.StatusOK)
        w.Write([]byte("Upload successful"))
    })

    log.Println("Starting server")
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        log.Fatal(err)
    }
}
1357 chars
47 lines

This code sets up an HTTP handler function that listens for /upload requests. When a request comes in, it uses r.ParseMultipartForm to parse the request body and extract any multipart form data. It then loops through any uploaded files and prints a summary of each file to the console. Finally, it sends a response to the client to indicate that the upload was successful.

You can also customize this code to handle other types of form data, handle errors differently, or perform other operations on the uploaded files.

gistlibby LogSnag