Skip to content

Commit

Permalink
feat: add last segment to content disposition
Browse files Browse the repository at this point in the history
  • Loading branch information
hacdias committed Jun 2, 2023
1 parent 9a9674b commit 26824e0
Showing 1 changed file with 17 additions and 7 deletions.
24 changes: 17 additions & 7 deletions gateway/handler_car.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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")

Expand Down Expand Up @@ -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 {
Expand Down

0 comments on commit 26824e0

Please sign in to comment.