/
handler_unixfs.go
51 lines (42 loc) · 1.47 KB
/
handler_unixfs.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package httpserver
import (
"context"
"fmt"
"net/http"
"github.com/ipfs/go-cid"
"github.com/ipfs/go-libipfs/files"
"github.com/ipfs/interface-go-ipfs-core/path"
)
// return true if is directory
func (hs *HttpServer) serveUnixFS(w http.ResponseWriter, r *http.Request, assetCID string) (bool, int, error) {
ctx, cancel := context.WithCancel(r.Context())
defer cancel()
root, err := cid.Decode(assetCID)
if err != nil {
return false, http.StatusBadRequest, fmt.Errorf("decode car cid error: %s", err.Error())
}
contentPath := path.New(r.URL.Path)
resolvedPath, err := hs.resolvePath(ctx, contentPath, root)
if err != nil {
return false, http.StatusBadRequest, fmt.Errorf("can not resolved path: %s", err.Error())
}
node, err := hs.getUnixFsNode(ctx, resolvedPath, root)
if err != nil {
return false, http.StatusInternalServerError, fmt.Errorf("error while getting UnixFS node: %s", err.Error())
}
defer node.Close() //nolint:errcheck // ignore error
// Handling Unixfs file
if f, ok := node.(files.File); ok {
log.Debugw("serving unixfs file", "path", contentPath)
statusCode, err := hs.serveFile(w, r, assetCID, f)
return false, statusCode, err
}
// Handling Unixfs directory
dir, ok := node.(files.Directory)
if !ok {
return false, http.StatusInternalServerError, fmt.Errorf("unsupported UnixFS type")
}
log.Debugw("serving unixfs directory", "path", contentPath)
statusCode, err := hs.serveDirectory(w, r, assetCID, dir)
return true, statusCode, err
}