a tool for handling file uploads for http servers
makes it easier to save multipart files from http request and to filter them, prevents unwanted files from getting into memory, extracts json data with files.
go get -u github.com/xis/baraka
func main() {
// create a storage
storage, err := baraka.NewStorage("./pics/", baraka.Options{})
if err != nil {
fmt.Println(err)
}
router := gin.Default()
router.POST("/upload", func(c *gin.Context) {
// parsing
p, err := storage.Parse(c.Request)
// or you can use ParseButMax if you need limited size
p, err := storage.ParseButMax(32<<20, 5, c.Request)
if err != nil {
fmt.Println(err)
}
// saving
p.Store("file_prefix")
})
router.Run()
}
you can use with other http server libraries, just pass the http.Request to storage.Parse function.
filter function is a custom function that filters the files that comes from requests. you can read file bytes and identify the file, return true if you wanna pass the file, return false if you dont.
// create a storage
func main() {
storage, err := baraka.NewStorage("./pics/", baraka.Options{
// passing filter function
Filter: func(file *multipart.Part) bool {
// create a byte array
b := make([]byte, 512)
// get the file bytes to created byte array
file.Read(b)
// detect the content type
fileType := http.DetectContentType(b)
// if it is jpeg then pass the file
if fileType == "image/jpeg" {
return true
}
// if not then don't pass
return false
},
})
...codes below...
... codes above ...
p, err := storage.Parse(c.Request)
if err != nil {
fmt.Println(err)
}
// prints filenames
fmt.Println(p.Filenames())
// prints total files count
fmt.Println(p.Length())
// prints content types of files
fmt.Println(p.ContentTypes())
... codes below ...
... codes above ...
p, err := storage.Parse(c.Request)
if err != nil {
fmt.Println(err)
}
b, err := p.JSON()
if err != nil {
fmt.Println(err)
}
var foo Foo
err := json.Unmarshal(b, foo)
if err != nil {
return err
}
... codes below ...
Handling file uploads simple and memory friendly in Go with Baraka
pull requests are welcome. please open an issue first to discuss what you would like to change.
please make sure to update tests as appropriate.