Skip to content
This repository was archived by the owner on Mar 23, 2023. It is now read-only.

Commit afe5a23

Browse files
authored
Merge pull request #18 from mayocream/fix_content_size
fix(api): content size
2 parents e3ae21c + e040cb4 commit afe5a23

File tree

1 file changed

+38
-10
lines changed

1 file changed

+38
-10
lines changed

server/handler.go

+38-10
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,10 @@ import (
44
"bytes"
55
"encoding/json"
66
"fmt"
7+
"mime/multipart"
78
"net/http"
89
"net/url"
10+
"os"
911
"path/filepath"
1012
"strings"
1113
"time"
@@ -63,11 +65,19 @@ func (s *Server) handleUpload(c *fiber.Ctx) error {
6365
if err != nil {
6466
return fiber.ErrBadRequest
6567
}
68+
69+
size, _ := multipartFileSize(fr)
70+
if size == 0 {
71+
// fallback
72+
size = f.Size
73+
}
74+
6675
defer fr.Close()
6776
blobs = append(blobs, &file{
6877
Name: f.Filename,
6978
MIMEType: mediaTypeOrDefault(f.Header),
7079
Reader: fr,
80+
Size: size,
7181
})
7282
}
7383
}
@@ -96,11 +106,11 @@ func (s *Server) handlePut(c *fiber.Ctx) error {
96106
return fiber.ErrBadRequest
97107
}
98108

99-
var err error
100-
fn, err = url.QueryUnescape(fn)
101-
if err != nil {
102-
return err
103-
}
109+
var err error
110+
fn, err = url.QueryUnescape(fn)
111+
if err != nil {
112+
return err
113+
}
104114

105115
body := c.Body()
106116
if len(body) == 0 {
@@ -153,12 +163,12 @@ func (s *Server) handleCat(c *fiber.Ctx) error {
153163
// return fiber.ErrBadRequest
154164
// }
155165

156-
filename, err := url.QueryUnescape(c.Params("file"))
157-
if err != nil {
158-
return err
159-
}
166+
filename, err := url.QueryUnescape(c.Params("file"))
167+
if err != nil {
168+
return err
169+
}
160170

161-
path := filepath.Join(cid, filename)
171+
path := filepath.Join(cid, filename)
162172
src, err := s.ipc.CatStream(path)
163173
if err != nil {
164174
zap.S().Errorf("ipfs cat err: %s", err)
@@ -168,3 +178,21 @@ func (s *Server) handleCat(c *fiber.Ctx) error {
168178
c.SendStream(src)
169179
return nil
170180
}
181+
182+
// ref: https://medium.com/dtoebe/how-to-get-a-multipart-file-size-in-golang-3ab4ab4c3e3
183+
func multipartFileSize(fr multipart.File) (int64, error) {
184+
switch t := fr.(type) {
185+
case *os.File:
186+
f, err := t.Stat()
187+
if err != nil {
188+
return 0, err
189+
}
190+
return f.Size(), nil
191+
default:
192+
sr, err := fr.Seek(0, 0)
193+
if err != nil {
194+
return 0, err
195+
}
196+
return sr, nil
197+
}
198+
}

0 commit comments

Comments
 (0)