refactor: optimize

This commit is contained in:
Derrick Hammer 2024-01-15 15:16:48 -05:00
parent 387ec56bec
commit 6784cbf453
Signed by: pcfreak30
GPG Key ID: C997C339BE476FF2
1 changed files with 10 additions and 12 deletions

View File

@ -40,7 +40,8 @@ func NewHttpHandler(portal interfaces.Portal) *HttpHandlerImpl {
} }
func (h *HttpHandlerImpl) SmallFileUpload(jc *jape.Context) { func (h *HttpHandlerImpl) SmallFileUpload(jc *jape.Context) {
buffer := bytes.NewBuffer(nil) var rs io.ReadSeeker
var bufferSize int64
r := jc.Request r := jc.Request
contentType := r.Header.Get("Content-Type") contentType := r.Header.Get("Content-Type")
@ -67,21 +68,18 @@ func (h *HttpHandlerImpl) SmallFileUpload(jc *jape.Context) {
} }
}(file) }(file)
// Copy file contents to buffer rs = file
_, err = io.Copy(buffer, file)
if jc.Check(errReadFile, err) != nil {
h.portal.Logger().Error(errReadFile, zap.Error(err))
return
}
} else { } else {
// For other content types, read the body into the buffer data, err := io.ReadAll(r.Body)
_, err := io.Copy(buffer, r.Body)
if jc.Check(errReadFile, err) != nil { if jc.Check(errReadFile, err) != nil {
h.portal.Logger().Error(errReadFile, zap.Error(err)) h.portal.Logger().Error(errReadFile, zap.Error(err))
return return
} }
buffer := bytes.NewReader(data)
bufferSize = int64(buffer.Len())
rs = buffer
defer func(Body io.ReadCloser) { defer func(Body io.ReadCloser) {
err := Body.Close() err := Body.Close()
if err != nil { if err != nil {
@ -90,7 +88,7 @@ func (h *HttpHandlerImpl) SmallFileUpload(jc *jape.Context) {
}(r.Body) }(r.Body)
} }
hash, err := h.portal.Storage().PutFile(bytes.NewReader(buffer.Bytes()), "s5", false) hash, err := h.portal.Storage().PutFile(rs, "s5", false)
if err != nil { if err != nil {
_ = jc.Error(errUploadingFileErr, http.StatusInternalServerError) _ = jc.Error(errUploadingFileErr, http.StatusInternalServerError)
@ -98,7 +96,7 @@ func (h *HttpHandlerImpl) SmallFileUpload(jc *jape.Context) {
return return
} }
cid, err := encoding.CIDFromHash(hash, uint64(len(buffer.Bytes())), types.CIDTypeRaw) cid, err := encoding.CIDFromHash(hash, uint64(bufferSize), types.CIDTypeRaw)
if err != nil { if err != nil {
_ = jc.Error(errUploadingFileErr, http.StatusInternalServerError) _ = jc.Error(errUploadingFileErr, http.StatusInternalServerError)