-
Notifications
You must be signed in to change notification settings - Fork 61
/
serve_download.go
46 lines (38 loc) · 1.19 KB
/
serve_download.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
package gql
import (
"context"
"fmt"
blocks "github.com/ipfs/go-block-format"
"github.com/ipfs/go-cid"
"net/http"
)
const downloadBlockPath = "/download/block/"
type BlockGetter interface {
Get(context.Context, cid.Cid) (blocks.Block, error)
}
// Serve downloads of raw blocks (for debugging purposes)
func serveDownload(ctx context.Context, mux *http.ServeMux, bstore BlockGetter) {
mux.HandleFunc(downloadBlockPath, func(writer http.ResponseWriter, request *http.Request) {
if len(request.URL.Path) <= len(downloadBlockPath) {
writeError(writer, fmt.Sprintf("url path too short: "+request.URL.Path))
return
}
cidstr := request.URL.Path[len(downloadBlockPath):]
c, err := cid.Parse(cidstr)
if err != nil {
writeError(writer, fmt.Sprintf("parsing payload cid "+cidstr+": "+err.Error()))
return
}
blk, err := bstore.Get(ctx, c)
if err != nil {
writeError(writer, fmt.Sprintf("getting block "+cidstr+": "+err.Error()))
return
}
writer.Header().Set("Content-Type", "application/vnd.ipld.raw")
_, _ = writer.Write(blk.RawData())
})
}
func writeError(writer http.ResponseWriter, s string) {
_, _ = writer.Write([]byte(s))
writer.WriteHeader(http.StatusBadRequest)
}