-
Notifications
You must be signed in to change notification settings - Fork 1
/
http.go
83 lines (69 loc) · 1.47 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
73
74
75
76
77
78
79
80
81
82
83
package dnoxy
import (
"errors"
"io/ioutil"
"net/http"
"github.com/miekg/dns"
log "github.com/sirupsen/logrus"
)
type HTTPHandlerOptions struct{}
func NewHTTPHandler(ex Exchanger, opts *HTTPHandlerOptions) (*HTTPHandler, error) {
return &HTTPHandler{
ex: ex,
}, nil
}
type HTTPHandler struct {
ex Exchanger
}
func (h *HTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var err error
status := http.StatusInternalServerError
defer func() {
if err != nil {
log.WithField("status", status).Errorf(err.Error())
w.WriteHeader(status)
w.Write([]byte(err.Error()))
}
}()
if r.Method != http.MethodPost {
status = http.StatusMethodNotAllowed
err = errors.New("method unsupported")
return
}
if r.Header.Get("Content-Type") != "application/dns-message" {
status = http.StatusBadRequest
err = errors.New("invalid content-type")
return
}
if r.Header.Get("Accept") != "application/dns-message" {
status = http.StatusNotAcceptable
err = errors.New("invalid accept header")
return
}
b, err := ioutil.ReadAll(r.Body)
if err != nil {
return
}
msg := new(dns.Msg)
err = msg.Unpack(b)
if err != nil {
return
}
resp, err := h.ex.Exchange(r.Context(), msg)
if err != nil {
return
}
rb, err := resp.Pack()
if err != nil {
return
}
w.WriteHeader(http.StatusOK)
_, err = w.Write(rb)
if err != nil {
return
}
log.WithFields(log.Fields{
"status": 200,
"question": msg.Question[0].String(),
}).Infof("responding")
}