create a http server and upload a file in go

main.go
package main

import (
    "fmt"
    "io"
    "net/http"
    "os"
)

func uploadFile(w http.ResponseWriter, r *http.Request) {
    file, handler, err := r.FormFile("file")
    if err != nil {
        fmt.Println("Error Retrieving the File")
        fmt.Println(err)
        return
    }
    defer file.Close()

    fmt.Printf("Uploaded File: %+v\n", handler.Filename)
    fmt.Printf("File Size: %+v\n", handler.Size)
    fmt.Printf("MIME Header: %+v\n", handler.Header)

    // Create a new file in the current directory
    // with the same name as the uploaded file
    dst, err := os.Create(handler.Filename)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    defer dst.Close()

    // Copy the uploaded file to the created file on the filesystem
    if _, err := io.Copy(dst, file); err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    fmt.Fprintf(w, "Successfully Uploaded File\n")
}

func setupRoutes() {
    http.HandleFunc("/upload", uploadFile)
    http.ListenAndServe(":8080", nil)
}

func main() {
    fmt.Println("Starting HTTP Server...")
    setupRoutes()
}
1186 chars
50 lines

This code creates an HTTP server in Go that listens on port 8080, and captures a file using a form and saves it to the current directory. The HTTP server is created using the http package built into Go. A function uploadFile is defined which handles the file upload. The setupRoutes function defines the route /upload and starts the server. The io and os libraries are used for reading the file and creating a new file respectively. The fmt library is used for outputting messages to the console.

related categories

gistlibby LogSnag