1
2
3
4
5
6 package httptest
7
8 import (
9 "bufio"
10 "bytes"
11 "context"
12 "crypto/tls"
13 "io"
14 "net/http"
15 "strings"
16 )
17
18
19 func NewRequest(method, target string, body io.Reader) *http.Request {
20 return NewRequestWithContext(context.Background(), method, target, body)
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 func NewRequestWithContext(ctx context.Context, method, target string, body io.Reader) *http.Request {
47 if method == "" {
48 method = "GET"
49 }
50 req, err := http.ReadRequest(bufio.NewReader(strings.NewReader(method + " " + target + " HTTP/1.0\r\n\r\n")))
51 if err != nil {
52 panic("invalid NewRequest arguments; " + err.Error())
53 }
54 req = req.WithContext(ctx)
55
56
57 req.Proto = "HTTP/1.1"
58 req.ProtoMinor = 1
59 req.Close = false
60
61 if body != nil {
62 switch v := body.(type) {
63 case *bytes.Buffer:
64 req.ContentLength = int64(v.Len())
65 case *bytes.Reader:
66 req.ContentLength = int64(v.Len())
67 case *strings.Reader:
68 req.ContentLength = int64(v.Len())
69 default:
70 req.ContentLength = -1
71 }
72 if rc, ok := body.(io.ReadCloser); ok {
73 req.Body = rc
74 } else {
75 req.Body = io.NopCloser(body)
76 }
77 }
78
79
80
81
82 req.RemoteAddr = "192.0.2.1:1234"
83
84 if req.Host == "" {
85 req.Host = "example.com"
86 }
87
88 if strings.HasPrefix(target, "https://") {
89 req.TLS = &tls.ConnectionState{
90 Version: tls.VersionTLS12,
91 HandshakeComplete: true,
92 ServerName: req.Host,
93 }
94 }
95
96 return req
97 }
98
View as plain text