Skip to content
Node: express, cors, helmet, morgangithub.com/sahilkhaire/gox/http

MultipartForm.ParseMultipart

Overview

ParseMultipart parses a multipart request (multer).

Part of the http package — Node.js analog: express, cors, helmet, morgan.

Method on MultipartForm — call it on a value of that type after constructing or receiving one from a constructor.

Signature

go
func ParseMultipart(c *Ctx, maxMemory int64) (*MultipartForm, error)

Compare: Node.js · Standard Go · gox

js
// Typical express, cors, helmet, morgan pattern in Node.js
go
func handler(w http.ResponseWriter, r *http.Request) {
    // chi or net/http
}
go
import "github.com/sahilkhaire/gox/http"

app := New()
dir := t.TempDir()
app.Post("/upload", func(c *Ctx) error {
	form, err := ParseMultipart(c, 1<<20)
	if err != nil {
		return err
	}
	files := form.Files("file")
	if len(files) != 1 {
		return goxerr.BadRequest("missing file")
	}
	dest := filepath.Join(dir, "out.txt")
	if err := SaveUploadedFile(files[0], dest); err != nil {
		return err
	}
	return c.JSON(200, map[string]string{"ok": "1"})
})
var body bytes.Buffer
w := multipart.NewWriter(&body)
part, _ := w.CreateFormFile("file", "x.txt")

Example

go
import "github.com/sahilkhaire/gox/http"

app := New()
dir := t.TempDir()
app.Post("/upload", func(c *Ctx) error {
	form, err := ParseMultipart(c, 1<<20)
	if err != nil {
		return err
	}
	files := form.Files("file")
	if len(files) != 1 {
		return goxerr.BadRequest("missing file")
	}
	dest := filepath.Join(dir, "out.txt")
	if err := SaveUploadedFile(files[0], dest); err != nil {
		return err
	}
	return c.JSON(200, map[string]string{"ok": "1"})
})
var body bytes.Buffer
w := multipart.NewWriter(&body)
part, _ := w.CreateFormFile("file", "x.txt")

Tips

Stack Logger, Recover, and Security middleware the way you would morgan + helmet in Express.

Standard library alternative

Use the standard library directly:

go
func handler(w http.ResponseWriter, r *http.Request) {
    // chi or net/http
}

Back to http package overview

MIT Licensed · Built for Node.js developers moving to Go