-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathserve_http.go
More file actions
128 lines (100 loc) · 2.21 KB
/
Copy pathserve_http.go
File metadata and controls
128 lines (100 loc) · 2.21 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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package wildcat
import (
"bufio"
"bytes"
"fmt"
"log"
"net"
"net/http"
"net/url"
"strings"
)
type adaptServeHTTP struct {
h http.Handler
}
func AdaptServeHTTP(h http.Handler) Handler {
return &adaptServeHTTP{h}
}
func (a *adaptServeHTTP) convertHeader(hp *HTTPParser) http.Header {
header := make(http.Header)
for _, h := range hp.Headers {
if h.Name == nil {
continue
}
header[string(h.Name)] = append(header[string(h.Name)], string(h.Value))
}
return header
}
func (a *adaptServeHTTP) HandleConnection(hp *HTTPParser, rest []byte, c net.Conn) {
u, err := url.Parse(fmt.Sprintf("http://%s/%s", string(hp.Host()), string(hp.Path)))
if err != nil {
log.Fatal(err)
return
}
var protoMajor int
var protoMinor int
switch string(hp.Version) {
case "HTTP/0.9":
protoMinor = 9
case "HTTP/1.0":
protoMajor = 1
case "HTTP/1.1":
protoMajor = 1
protoMinor = 1
}
req := http.Request{
Method: string(hp.Method),
URL: u,
Proto: string(hp.Version),
ProtoMajor: protoMajor,
ProtoMinor: protoMinor,
Header: a.convertHeader(hp),
Body: hp.BodyReader(rest, c),
ContentLength: hp.ContentLength(),
Host: string(hp.Host()),
RequestURI: string(hp.Path),
RemoteAddr: c.RemoteAddr().String(),
}
w := &responseWriter{c: c}
w.init()
a.h.ServeHTTP(w, &req)
c.Close()
}
type responseWriter struct {
c net.Conn
code int
header http.Header
wroteHeader bool
}
func (r *responseWriter) init() {
r.code = 200
r.header = make(http.Header)
}
func (r *responseWriter) Header() http.Header {
return r.header
}
func (r *responseWriter) WriteHeader(code int) {
if r.wroteHeader {
return
}
var buf bytes.Buffer
for k, v := range r.header {
buf.WriteString(k)
buf.WriteString(": ")
if len(v) == 1 {
buf.WriteString(v[0])
} else {
buf.WriteString(strings.Join(v, ", "))
}
buf.WriteString("\r\n")
}
r.c.Write(buf.Bytes())
r.wroteHeader = true
}
func (r *responseWriter) Write(buf []byte) (int, error) {
r.WriteHeader(r.code)
return r.c.Write(buf)
}
func (r *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return r.c, bufio.NewReadWriter(bufio.NewReader(r.c), bufio.NewWriter(r.c)), nil
}