Skip to content

Instantly share code, notes, and snippets.

@cmhobbs
Created August 3, 2012 04:21
Show Gist options
  • Save cmhobbs/3244341 to your computer and use it in GitHub Desktop.
Save cmhobbs/3244341 to your computer and use it in GitHub Desktop.
Handling multipart file uploads with goweb
package main
import (
"code.google.com/p/goweb/goweb"
"io/ioutil"
)
// dummy error struct for pretty json export
type ControllerError struct {
Error error
}
type UploadController struct{}
/*
Multi-part form named "file". This retrieves a binary file from
the request body and saves it to incoming/filename. You will
need to create the incoming directory in the same path as the
uploader.
Because cx.Request is simply a net/http struct, we can work with
it accordingly. In this example, the "description" value is
taken and returned to the requestor.
Example - Upload the goweb source archive with HTTPie:
http -f POST localhost:8080/uploader description="goweb source archive" file@goweb-v1.3.zip
This should store the file locally and return the following if
all goes well:
{
"C": "",
"D": "Uploaded: goweb-v1.3.zip - goweb source archive",
"E": null,
"S": 200
}
*/
func (cr *UploadController) Create(cx *goweb.Context) {
binpath := "incoming/"
file, handler, err := cx.Request.FormFile("file")
if err != nil {
cx.RespondWithData(ControllerError{err})
}
data, err := ioutil.ReadAll(file)
if err != nil {
cx.RespondWithData(ControllerError{err})
}
err = ioutil.WriteFile(binpath+handler.Filename, data, 0777)
if err != nil {
cx.RespondWithData(ControllerError{err})
}
cx.RespondWithData("Uploaded: " + handler.Filename + " - " + cx.Request.FormValue("description"))
}
// make rocket go now
func main() {
goweb.ConfigureDefaultFormatters() // default to JSON
uploader := new(UploadController)
goweb.MapRest("/uploader", uploader)
goweb.ListenAndServe(":8080")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment