Skip to content

xis/baraka

Repository files navigation

baraka

Go Report Card codecov Build Status go.dev reference

a tool for handling file uploads for http servers

makes it easier to make operations with files from the http request.

install

go get github.com/xis/baraka/v2

usage

func main() {
	// create a parser
	parser := baraka.NewParser(baraka.ParserOptions{
		MaxFileSize:   5 << 20,
		MaxFileCount:  5,
		MaxParseCount: 5,
	})

	router := gin.Default()
	router.POST("/upload", func(c *gin.Context) {
		// parsing
		p, err := parser.Parse(c.Request)
		if err != nil {
			fmt.Println(err)
		}
		// saving
		err = p.Save("image_", "./")
		if err != nil {
			fmt.Println(err)
		}
		// getting the part in the []byte format
		parts := p.Content()
		buf := parts[0].Content
		fmt.Println(len(buf))
	})
	router.Run()
}

you can use baraka with the other http server libraries, just pass the http.Request to the parser.Parse function.

filter function

filter function is a custom function which filters the files that comes from the request. for example you can read file bytes and identify the file, return true if you wanna pass the file, return false if you don't.

filter example

func main() {
	// create a parserr
	parser := baraka.NewParser(baraka.ParserOptions{
		// passing filter function
		Filter: func(data []byte) bool {
			// get first 512 bytes for checking content type
			buf := data[:512]
			// detect the content type
			fileType := http.DetectContentType(buf)
			// if it is jpeg then pass the file
			if fileType == "image/jpeg" {
				return true
			}
			// if not then don't pass
			return false
		},
	})

getting information

p, err := parser.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())

getting json data

p, err := parser.Parse(c.Request)
if err != nil {
   fmt.Println(err)
}
jsonStrings, err := p.GetJSON()
if err != nil {
   fmt.Println(err)
}

more

v1.1.1 Handling file uploads simple and memory friendly in Go with Baraka

contributing

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.

license

MIT