Skip to content

Commit

Permalink
feat(gateway): generate content type form car params
Browse files Browse the repository at this point in the history
  • Loading branch information
hacdias committed Jun 22, 2023
1 parent 2f2e7f2 commit fbc17b5
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
25 changes: 24 additions & 1 deletion gateway/handler_car.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ func (i *handler) serveCAR(ctx context.Context, w http.ResponseWriter, r *http.R
// sub-DAGs and IPLD selectors: https://github.com/ipfs/go-ipfs/issues/8769
w.Header().Set("Accept-Ranges", "none")

w.Header().Set("Content-Type", carResponseFormat+"; version=1")
w.Header().Set("Content-Type", getContentTypeFromCarParams(params))
w.Header().Set("X-Content-Type-Options", "nosniff") // no funny business in the browsers :^)

_, copyErr := io.Copy(w, carFile)
Expand All @@ -113,6 +113,29 @@ func (i *handler) serveCAR(ctx context.Context, w http.ResponseWriter, r *http.R
return true
}

func getContentTypeFromCarParams(params CarParams) string {
h := strings.Builder{}
h.WriteString(carResponseFormat)
h.WriteString("; version=1; order=")

if params.Order != "" {
h.WriteString(string(params.Order))
} else {
h.WriteString(string(DagOrderUnknown))
}

if params.Duplicates != nil {
h.WriteString("; dups=")
if *params.Duplicates {
h.WriteString("y")
} else {
h.WriteString("n")
}
}

return h.String()
}

func getCarParams(r *http.Request, formatParams map[string]string) (CarParams, error) {
queryParams := r.URL.Query()
rangeStr, hasRange := queryParams.Get(carRangeBytesKey), queryParams.Has(carRangeBytesKey)
Expand Down
23 changes: 23 additions & 0 deletions gateway/handler_car_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,29 @@ func TestCarParams(t *testing.T) {
})
}

func TestContentTypeFromCarParams(t *testing.T) {
t.Parallel()

T := true
F := false

tests := []struct {
params CarParams
header string
}{
{CarParams{}, "application/vnd.ipld.car; version=1; order=unk"},
{CarParams{Order: DagOrderDFS, Duplicates: &T}, "application/vnd.ipld.car; version=1; order=dfs; dups=y"},
{CarParams{Order: DagOrderUnknown, Duplicates: &T}, "application/vnd.ipld.car; version=1; order=unk; dups=y"},
{CarParams{Order: DagOrderUnknown}, "application/vnd.ipld.car; version=1; order=unk"},
{CarParams{Duplicates: &T}, "application/vnd.ipld.car; version=1; order=unk; dups=y"},
{CarParams{Duplicates: &F}, "application/vnd.ipld.car; version=1; order=unk; dups=n"},
}
for _, test := range tests {
header := getContentTypeFromCarParams(test.params)
assert.Equal(t, test.header, header)
}
}

func TestGetCarEtag(t *testing.T) {
t.Parallel()

Expand Down

0 comments on commit fbc17b5

Please sign in to comment.