summaryrefslogtreecommitdiff
path: root/http/files.go
blob: 06e5fd2447c3b6429603d239a4f9ee260961290d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package http

import (
	"mime/multipart"
	"strings"
	"github.com/sirupsen/logrus"
)

type fileData map[string]interface{}

type FileUpload struct {
	Name     string `json:"name"`
	MimeType string `json:"mimetype"`
}

func (d fileData) push(k string, v []*multipart.FileHeader) {
	if len(v) == 0 {
		// doing nothing
		return
	}

	chunks := make([]string, 0)
	for _, chunk := range strings.Split(k, "[") {
		chunks = append(chunks, strings.Trim(chunk, "]"))
	}

	d.pushChunk(chunks, v)
}

func (d fileData) pushChunk(k []string, v []*multipart.FileHeader) {
	logrus.Print(v)
	if len(v) == 0 || v[0] == nil {
		return
	}

	head := k[0]
	tail := k[1:]
	if len(k) == 1 {
		d[head] = FileUpload{
			Name:     v[0].Filename,
			MimeType: v[0].Header.Get("Content-Type"),
		}
		return
	}

	// unnamed array
	if len(tail) == 1 && tail[0] == "" {
		d[head] = v
		return
	}

	if p, ok := d[head]; !ok {
		d[head] = make(fileData)
		d[head].(fileData).pushChunk(tail, v)
	} else {
		p.(fileData).pushChunk(tail, v)
	}
}