create a http server and upload a file and return a binary response in go

To create an HTTP server and handle file uploads, we can use the net/http package. Here is an example code snippet that shows how to do this:

main.go
package main

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

func handleUpload(w http.ResponseWriter, r *http.Request) {
    // Set max file size to 2MB
    r.ParseMultipartForm(2 << 20)

    // Get the file from the request
    file, handler, err := r.FormFile("file")
    if err != nil {
        log.Println("Error retrieving file", err)
        return
    }
    defer file.Close()

    // Read the content of the file
    fileBytes, err := ioutil.ReadAll(file)
    if err != nil {
        log.Println("Error reading file content", err)
        return
    }

    // Calculate the size of the file
    fileSize := len(fileBytes)

    // Return a binary response with the file content and size
    w.Header().Set("Content-Type", "application/octet-stream")
    w.Header().Set("Content-Disposition", "attachment; filename="+handler.Filename)
    w.Header().Set("Content-Length", fmt.Sprint(fileSize))
    w.Write(fileBytes)
}

func main() {
    http.HandleFunc("/upload", handleUpload)
    log.Fatal(http.ListenAndServe(":8080", nil))
}
1052 chars
43 lines

In this code, we define a handleUpload function that handles the file upload request. It reads the file from the request using the r.FormFile method, reads the content of the file using the ioutil.ReadAll method, and calculates the size of the file using the len function. Finally, it returns a binary response with the file content and size using the w.Write method.

We then register this function as a handler for the /upload route using the http.HandleFunc method and start the server using the http.ListenAndServe method.

gistlibby LogSnag