DEV Community

Cover image for How to POST multipart/form-data in GO using Mux
vasubabu
vasubabu

Posted on

How to POST multipart/form-data in GO using Mux

Mux is a powerful HTTP router that matches incoming requests against a list of registered routes and calls a handler for the route that matches the URL or other conditions.

Enough talking ....

Please create a new file called main.go and paste the below contents

package main

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

func UploadFile(w http.ResponseWriter, r *http.Request) {
    file, handler, err := r.FormFile("file")
    fileName := r.FormValue("file_name")
    if err != nil {
        panic(err)
    }
    defer file.Close()

    f, err := os.OpenFile(handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
    if err != nil {
        panic(err)
    }
    defer f.Close()
    _, _ = io.WriteString(w, "File "+fileName+" Uploaded successfully")
    _, _ = io.Copy(f, file)
}

func homeLink(w http.ResponseWriter, r *http.Request) {
    _, _ = fmt.Fprintf(w, "Welcome home!")
}

func main() {
    router := mux.NewRouter().StrictSlash(true)
    router.HandleFunc("/", homeLink)
    router.HandleFunc("/file", UploadFile).Methods("POST")
    log.Fatal(http.ListenAndServe(":8081", router))
}

Build it - go build

Run it - go run main.go

Test it - Using Postman/Curl

Postman:

alt text

CURL:

curl -X POST \
  http://localhost:8081/file \
  -H 'Accept: */*' \
  -H 'Accept-Encoding: gzip, deflate' \
  -H 'Cache-Control: no-cache' \
  -H 'Connection: keep-alive' \
  -H 'Content-Length: 4251' \
  -H 'Content-Type: multipart/form-data; boundary=--------------------------489143350034706567613009' \
  -H 'Host: localhost:8081' \
  -H 'Postman-Token: fea94e80-8294-4f0b-87bf-09b706eddac8,1bbb735b-f88d-4194-a1b5-f8cd90189545' \
  -H 'User-Agent: PostmanRuntime/7.17.1' \
  -H 'cache-control: no-cache' \
  -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \
  -F file=@/Users/vasubabujinagam/Documents/protobuf-3.9.2/CONTRIBUTORS.txt \
  -F file_name=file1

Oldest comments (1)

Collapse
 
lacutee profile image
Ridho Muhammad

Hii thanks for the article its really helpfull. But i got error when trying to upload the f which is file the copyied from file at line _, _ := io.Copy(f, file).

So the problem when i upload f cloudinary using this
uploadResult, err := cld.Upload.Upload(ctx, f, uploader.UploadParams{})

err return access denied, i also had trying to change permision at .OpenFile() from 0666 to 0777 but its still the same