-
Notifications
You must be signed in to change notification settings - Fork 1
/
context.go
60 lines (46 loc) · 1.27 KB
/
context.go
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
59
60
package gulter
import (
"context"
"net/http"
)
type contextKey string
const (
fileKey contextKey = "files"
)
type errorMsg string
func (e errorMsg) Error() string { return string(e) }
const (
ErrNoFilesUploaded = errorMsg("gulter: no uploadable files found in request")
)
type Files map[string][]File
func writeFilesToContext(ctx context.Context,
f Files,
) context.Context {
existingFiles, ok := ctx.Value(fileKey).(Files)
if !ok {
existingFiles = Files{}
}
for _, v := range f {
// all the files should have the same form field,
// so safe to use any index
existingFiles[v[0].FieldName] = append(existingFiles[v[0].FieldName], v...)
}
return context.WithValue(ctx, fileKey, existingFiles)
}
// FilesFromContext returns all files that have been uploaded during the request
func FilesFromContext(r *http.Request) (Files, error) {
files, ok := r.Context().Value(fileKey).(Files)
if !ok {
return nil, ErrNoFilesUploaded
}
return files, nil
}
// FilesFromContextWithKey returns all files that have been uploaded during the request
// and sorts by the provided form field
func FilesFromContextWithKey(r *http.Request, key string) ([]File, error) {
files, ok := r.Context().Value(fileKey).(Files)
if !ok {
return nil, ErrNoFilesUploaded
}
return files[key], nil
}