-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrouting.go
More file actions
113 lines (92 loc) · 2.25 KB
/
routing.go
File metadata and controls
113 lines (92 loc) · 2.25 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package main
import (
"context"
"fmt"
"io"
"net/http"
"strings"
"github.com/ipfs/boxo/ipns"
"github.com/libp2p/go-libp2p/core/routing"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
)
type proxyRouting struct {
gatewayURL string
httpClient *http.Client
}
func newProxyRouting(gatewayURL string, client *http.Client) routing.ValueStore {
if client == nil {
client = &http.Client{
Transport: otelhttp.NewTransport(http.DefaultTransport),
}
}
return &proxyRouting{
gatewayURL: gatewayURL,
httpClient: client,
}
}
func (ps *proxyRouting) PutValue(context.Context, string, []byte, ...routing.Option) error {
return routing.ErrNotSupported
}
func (ps *proxyRouting) GetValue(ctx context.Context, k string, opts ...routing.Option) ([]byte, error) {
if !strings.HasPrefix(k, "/ipns/") {
return nil, routing.ErrNotSupported
}
name, err := ipns.NameFromRoutingKey([]byte(k))
if err != nil {
return nil, err
}
return ps.fetch(ctx, name)
}
func (ps *proxyRouting) SearchValue(ctx context.Context, k string, opts ...routing.Option) (<-chan []byte, error) {
if !strings.HasPrefix(k, "/ipns/") {
return nil, routing.ErrNotSupported
}
name, err := ipns.NameFromRoutingKey([]byte(k))
if err != nil {
return nil, err
}
ch := make(chan []byte)
go func() {
v, err := ps.fetch(ctx, name)
if err != nil {
close(ch)
} else {
ch <- v
close(ch)
}
}()
return ch, nil
}
func (ps *proxyRouting) fetch(ctx context.Context, name ipns.Name) ([]byte, error) {
urlStr := fmt.Sprintf("%s/ipns/%s", ps.gatewayURL, name.String())
req, err := http.NewRequestWithContext(ctx, http.MethodGet, urlStr, nil)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/vnd.ipfs.ipns-record")
resp, err := ps.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("unexpected status from remote gateway: %s", resp.Status)
}
rb, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
rec, err := ipns.UnmarshalRecord(rb)
if err != nil {
return nil, err
}
err = ipns.ValidateWithName(rec, name)
if err != nil {
return nil, err
}
return rb, nil
}