-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy pathupdown.go
97 lines (83 loc) · 2.33 KB
/
updown.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package uploaddownload
import (
"context"
"io"
"log"
"mime"
"mime/multipart"
"os"
"path/filepath"
updown "goa.design/examples/upload_download/gen/updown"
)
// updown service example implementation.
// The example methods log the requests and return zero values.
type updownsrvc struct {
dir string // Path to download and upload directory
logger *log.Logger
}
// NewUpdown returns the updown service implementation.
func NewUpdown(dir string, logger *log.Logger) (updown.Service, error) {
abs, err := filepath.Abs(dir)
if err != nil {
return nil, err
}
if _, err := os.Stat(abs); err != nil {
return nil, err
}
return &updownsrvc{abs, logger}, nil
}
// Upload implements upload.
func (s *updownsrvc) Upload(ctx context.Context, p *updown.UploadPayload, req io.ReadCloser) error {
// Don't forget to close the body reader!
defer req.Close()
// Make sure upload directory exists
uploadDir := filepath.Join(s.dir, p.Dir)
if err := os.MkdirAll(uploadDir, 0777); err != nil {
return updown.MakeInternalError(err)
}
// Createa multipart request reader
_, params, err := mime.ParseMediaType(p.ContentType)
if err != nil {
return updown.MakeInvalidMediaType(err)
}
mr := multipart.NewReader(req, params["boundary"])
// Go through each part and save the corresponding content to disk.
for {
part, err := mr.NextPart()
if err == io.EOF {
// We're done!
return nil
}
if err != nil {
return updown.MakeInvalidMultipartRequest(err)
}
// Create uploaded file, potentially overridding existing file.
fpath := filepath.Join(uploadDir, part.FileName())
f, err := os.Create(fpath)
if err != nil {
return updown.MakeInternalError(err)
}
defer f.Close()
// Stream content to disk.
n, err := io.Copy(f, part)
if err != nil {
return updown.MakeInternalError(err)
}
s.logger.Printf("Written %d bytes to %q", n, fpath)
}
}
// Download implements download.
func (s *updownsrvc) Download(ctx context.Context, p string) (*updown.DownloadResult, io.ReadCloser, error) {
// Locate file to download.
abs := filepath.Join(s.dir, p)
fi, err := os.Stat(abs)
if err != nil {
return nil, nil, updown.MakeInvalidFilePath(err)
}
// Open file for streaming
f, err := os.Open(abs)
if err != nil {
return nil, nil, updown.MakeInternalError(err)
}
return &updown.DownloadResult{Length: fi.Size()}, f, nil
}