-
Notifications
You must be signed in to change notification settings - Fork 0
/
nip11.go
108 lines (104 loc) · 2.37 KB
/
nip11.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
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
package main
import (
"bufio"
"bytes"
"compress/gzip"
"encoding/json"
"fmt"
"io"
"strconv"
"strings"
"github.com/nbd-wtf/go-nostr/nip11"
)
func NIP11_fetch(conn io.ReadWriter, hostname string) (*nip11.RelayInformationDocument, error) {
wb := bufio.NewWriter(conn)
wb.Write([]byte("GET / HTTP/1.1\r\n"))
wb.Write([]byte(fmt.Sprintf("Host: %s\r\n", hostname)))
wb.Write([]byte("User-Agent: barkyq-http-client/1.0\r\n"))
wb.Write([]byte("Accept: application/nostr+json\r\n"))
wb.Write([]byte("Accept-Encoding: gzip\r\n"))
wb.Write([]byte("\r\n"))
wb.Flush()
rb := bufio.NewReader(conn)
// read the headers
var chunked bool
var content_encoding string
for {
header_line, err := rb.ReadString('\n')
if err != nil {
return nil, err
}
if arr := strings.Split(header_line, ":"); len(arr) > 1 {
key := strings.TrimSpace(strings.ToLower(arr[0]))
val := strings.TrimSpace(strings.ToLower(arr[1]))
switch key {
case "transfer-encoding":
if val == "chunked" {
chunked = true
}
case "content-encoding":
content_encoding = val
default:
}
}
if header_line == "\r\n" {
// break at the empty CRLF
break
}
}
var nip11_reader io.Reader
if chunked {
var tmp [32]byte
data_buf := bytes.NewBuffer(nil)
for {
chunk, err := rb.ReadString('\n')
if err != nil {
return nil, err
}
chunk_size, err := strconv.ParseInt(strings.TrimSpace(chunk), 16, 64)
if err != nil {
return nil, err
}
if chunk_size == 0 {
rb.Discard(2)
// finished chunking
break
}
for chunk_size > 32 {
if n, err := rb.Read(tmp[:]); err == nil {
chunk_size -= int64(n)
data_buf.Write(tmp[:n])
} else {
return nil, err
}
}
if n, err := rb.Read(tmp[:chunk_size]); err == nil {
data_buf.Write(tmp[:n])
}
// chunk size does not account for CRLF added to end of chunk data
rb.Discard(2)
}
nip11_reader = data_buf
} else {
nip11_reader = rb
}
var dec *json.Decoder
switch content_encoding {
case "gzip":
if r, err := gzip.NewReader(nip11_reader); err != nil {
return nil, err
} else {
dec = json.NewDecoder(r)
}
default:
dec = json.NewDecoder(nip11_reader)
}
info := nip11.RelayInformationDocument{}
if e := dec.Decode(&info); e != nil {
return nil, e
}
if rb.Buffered() != 0 {
return &info, fmt.Errorf("unread bytes trapped in bufio.Reader")
}
return &info, nil
}