frostfs-http-gw/receive.go

110 lines
2.4 KiB
Go
Raw Normal View History

package main
import (
"io"
"net/http"
"path"
"strconv"
2020-11-09 13:43:23 +00:00
"strings"
"sync"
"time"
2020-11-09 13:43:23 +00:00
sdk "github.com/nspcc-dev/cdn-neofs-sdk"
"github.com/nspcc-dev/neofs-api-go/pkg/object"
2020-04-22 10:34:48 +00:00
"github.com/pkg/errors"
"github.com/valyala/fasthttp"
"go.uber.org/zap"
2020-04-22 10:34:48 +00:00
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
2020-11-09 13:43:23 +00:00
type detector struct {
io.Writer
sync.Once
contentType string
}
func newDetector(w io.Writer) *detector {
return &detector{Writer: w}
}
func (d *detector) Write(data []byte) (int, error) {
d.Once.Do(func() {
d.contentType = http.DetectContentType(data)
})
return d.Writer.Write(data)
}
func (a *app) receiveFile(c *fasthttp.RequestCtx) {
var (
err error
2020-11-09 13:43:23 +00:00
disp = "inline"
start = time.Now()
2020-11-09 13:43:23 +00:00
address = object.NewAddress()
sCID, _ = c.UserValue("cid").(string)
sOID, _ = c.UserValue("oid").(string)
2020-11-09 13:43:23 +00:00
value = strings.Join([]string{sCID, sOID}, "/")
filename string
)
log := a.log.With(
2020-02-25 10:31:20 +00:00
// zap.String("node", con.Target()),
zap.String("cid", sCID),
zap.String("oid", sOID))
2020-11-09 13:43:23 +00:00
if err = address.Parse(value); err != nil {
log.Error("wrong object address", zap.Error(err))
c.Error("wrong object address", fasthttp.StatusBadRequest)
return
}
2020-11-09 13:43:23 +00:00
writer := newDetector(c.Response.BodyWriter())
obj, err := a.cli.Object().Get(c, address, sdk.WithGetWriter(writer))
if err != nil {
log.Error("could not receive object",
zap.Stringer("elapsed", time.Since(start)),
zap.Error(err))
2020-04-22 10:34:48 +00:00
var (
msg = errors.Wrap(err, "could not receive object").Error()
code = fasthttp.StatusBadRequest
)
if st, ok := status.FromError(errors.Cause(err)); ok && st != nil {
if st.Code() == codes.NotFound {
code = fasthttp.StatusNotFound
}
msg = st.Message()
}
2020-04-22 10:34:48 +00:00
c.Error(msg, code)
return
}
2020-11-09 13:43:23 +00:00
if c.Request.URI().QueryArgs().GetBool("download") {
disp = "attachment"
}
2020-11-09 13:43:23 +00:00
c.Response.Header.Set("Content-Length", strconv.FormatUint(obj.GetPayloadSize(), 10))
c.Response.Header.Set("x-object-id", obj.GetID().String())
c.Response.Header.Set("x-owner-id", obj.GetOwnerID().String())
c.Response.Header.Set("x-container-id", obj.GetContainerID().String())
2020-11-09 13:43:23 +00:00
for _, attr := range obj.GetAttributes() {
key := attr.GetKey()
val := attr.GetValue()
if key == object.AttributeFileName {
filename = val
}
2020-11-09 13:43:23 +00:00
c.Response.Header.Set("x-"+key, val)
}
2020-11-09 13:43:23 +00:00
c.SetContentType(writer.contentType)
c.Response.Header.Set("Content-Disposition", disp+"; filename="+path.Base(filename))
}