Home > Backend Development > Golang > How to Receive and Process Uploaded Files in Go using net/http?

How to Receive and Process Uploaded Files in Go using net/http?

Barbara Streisand
Release: 2024-12-12 16:43:10
Original
323 people have browsed it

How to Receive and Process Uploaded Files in Go using net/http?

Receiving Uploaded Files with Golang and net/http

When working with an HTTP server, it's common to handle file uploads. In Go, using the net/http package, you can set up endpoints to receive and process uploaded files.

Consider the following code snippet:

package main

import (
    "fmt"
    "github.com/gorilla/mux"
    "net/http"
)

func main() {
...
    // Assuming you already have a router setup, add the following:
    router.
        Path("/upload").
        Methods("POST").
        HandlerFunc(uploadFile)
...
}
Copy after login

Inside the uploadFile function, you need to parse the uploaded file from the request:

func uploadFile(w http.ResponseWriter, r *http.Request) {
    err := r.ParseMultipartForm(5 * 1024 * 1024)
    if err != nil {
        panic(err)
    }
    // Get the file from the form
    file, header, err := r.FormFile("file")
    if err != nil {
        panic(err)
    }
...
}
Copy after login

The file object represents the uploaded file, while header provides information about the file, such as its filename and size. You can then work with the file contents as needed.

For example, you could save the file to disk:

    f, err := os.Create(header.Filename)
    if err != nil {
        log.Fatal(err)
    }
    defer f.Close()
    if _, err := io.Copy(f, file); err != nil {
        log.Fatal(err)
    }
...
Copy after login

Alternatively, you could process the file contents directly:

    defer file.Close()
    data, err := ioutil.ReadAll(file)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(string(data))
...
Copy after login

In this way, you can receive and handle uploaded files using Go's net/http package.

The above is the detailed content of How to Receive and Process Uploaded Files in Go using net/http?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template