-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathexchanger_http.go
67 lines (54 loc) · 1.21 KB
/
exchanger_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
package dnoxy
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"net/http"
"github.com/miekg/dns"
)
type HTTPExchangerOptions struct{}
func NewHTTPExchanger(url string, opts *HTTPExchangerOptions) (*HTTPExchanger, error) {
return &HTTPExchanger{
url: url,
client: &http.Client{},
opts: opts,
}, nil
}
// TODO remove after dev
var _ Exchanger = &HTTPExchanger{}
type HTTPExchanger struct {
url string
client *http.Client
opts *HTTPExchangerOptions
}
func (h *HTTPExchanger) Exchange(ctx context.Context, m *dns.Msg) (*dns.Msg, error) {
b, err := m.Pack()
if err != nil {
return nil, err
}
payload := bytes.NewReader(b)
req, err := http.NewRequest(http.MethodPost, h.url, payload)
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
req.Header.Add("Accept", "application/dns-message")
req.Header.Add("Content-Type", "application/dns-message")
resp, err := h.client.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("unexpected status: %v", resp.Status)
}
rb, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
r := new(dns.Msg)
if err := r.Unpack(rb); err != nil {
return nil, err
}
return r, nil
}