/
http.go
72 lines (65 loc) · 1.88 KB
/
http.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package mockdelegatedrouter
import (
"encoding/json"
"net/http"
"path"
"github.com/filecoin-project/storetheindex/api/v0/finder/model"
"github.com/ipfs/go-cid"
"github.com/libp2p/go-libp2p-core/peer"
"github.com/multiformats/go-multihash"
"github.com/multiformats/go-varint"
)
// A MockDelegatedProvider is the state of the http server acting as a counterparty
// to the HTTP delegated client.
type MockDelegatedProvider struct {
http.Server
records map[string]model.MultihashResult
}
// OnReq handles requests from the http delegated routing client
func (m *MockDelegatedProvider) OnReq(resp http.ResponseWriter, req *http.Request) {
_, queryCid := path.Split(req.URL.Path)
mh, err := multihash.FromB58String(queryCid)
if err != nil {
resp.WriteHeader(http.StatusNotAcceptable)
return
}
if qresp, ok := m.records[string(mh)]; ok {
outBytes, err := json.Marshal(model.FindResponse{
MultihashResults: []model.MultihashResult{qresp},
})
if err != nil {
resp.WriteHeader(http.StatusInternalServerError)
return
}
resp.Write(outBytes)
} else {
resp.WriteHeader(http.StatusNotFound)
return
}
}
// New creates a mock provider that can serve as a counterpart to the http
// delegated content routing client
func New() *MockDelegatedProvider {
mdp := MockDelegatedProvider{}
mux := http.NewServeMux()
mux.HandleFunc("/", mdp.OnReq)
mdp.Server.Handler = mux
mdp.records = make(map[string]model.MultihashResult)
return &mdp
}
// Add adds a record for the provider to return.
func (m *MockDelegatedProvider) Add(c cid.Cid, peerAddr peer.AddrInfo, protocol uint64, md []byte) error {
mdp := varint.ToUvarint(protocol)
md = append(mdp, md...)
m.records[string(c.Hash())] = model.MultihashResult{
Multihash: c.Hash(),
ProviderResults: []model.ProviderResult{
{
ContextID: []byte("something"),
Metadata: md,
Provider: peerAddr,
},
},
}
return nil
}