From 26824e043419025cd1cab6a960bfc3355f92a29a Mon Sep 17 00:00:00 2001 From: Henrique Dias Date: Thu, 1 Jun 2023 13:39:18 +0200 Subject: [PATCH] feat: add last segment to content disposition --- gateway/handler_car.go | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/gateway/handler_car.go b/gateway/handler_car.go index 78761b5a6..a9df55dd2 100644 --- a/gateway/handler_car.go +++ b/gateway/handler_car.go @@ -46,7 +46,7 @@ func (i *handler) serveCAR(ctx context.Context, w http.ResponseWriter, r *http.R return false } - rootCid, err := getCarRootCid(imPath) + rootCid, lastSegment, err := getCarRootCidAndLastSegment(imPath) if err != nil { i.webError(w, r, err, http.StatusInternalServerError) return false @@ -59,7 +59,11 @@ func (i *handler) serveCAR(ctx context.Context, w http.ResponseWriter, r *http.R if urlFilename := r.URL.Query().Get("filename"); urlFilename != "" { name = urlFilename } else { - name = rootCid.String() + ".car" + name = rootCid.String() + if lastSegment != "" { + name += "_" + lastSegment + } + name += ".car" } setContentDispositionHeader(w, name, "attachment") @@ -177,19 +181,25 @@ func rangeStrToByteRange(rangeStr string) (DagEntityByteRange, error) { }, nil } -func getCarRootCid(imPath ImmutablePath) (cid.Cid, error) { +func getCarRootCidAndLastSegment(imPath ImmutablePath) (cid.Cid, string, error) { imPathStr := imPath.String() if !strings.HasPrefix(imPathStr, "/ipfs/") { - return cid.Undef, fmt.Errorf("path does not have /ipfs/ prefix") + return cid.Undef, "", fmt.Errorf("path does not have /ipfs/ prefix") } - firstSegment, _, _ := strings.Cut(imPathStr[6:], "/") + firstSegment, remainingSegments, _ := strings.Cut(imPathStr[6:], "/") rootCid, err := cid.Decode(firstSegment) if err != nil { - return cid.Undef, err + return cid.Undef, "", err + } + + // Almost like path.Base(remainingSegments), but without special case for empty strings. + lastSegment := strings.TrimRight(remainingSegments, "/") + if i := strings.LastIndex(lastSegment, "/"); i >= 0 { + lastSegment = lastSegment[i+1:] } - return rootCid, err + return rootCid, lastSegment, err } func getCarEtag(r *http.Request, imPath ImmutablePath, params CarParams, rootCid cid.Cid) string {