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