-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequest_test.go
More file actions
96 lines (90 loc) · 2.2 KB
/
request_test.go
File metadata and controls
96 lines (90 loc) · 2.2 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
// Copyright (c) 2020 Meng Huang (mhboy@outlook.com)
// This package is licensed under a MIT license that can be found in the LICENSE file.
package request
import (
"bufio"
"github.com/hslam/response"
"io/ioutil"
"net"
"net/http"
"sync"
"testing"
"time"
)
func testHTTP(method, url string, status int, result string, t *testing.T) {
var req *http.Request
req, _ = http.NewRequest(method, url, nil)
client := &http.Client{
Transport: &http.Transport{
MaxConnsPerHost: 1,
DisableKeepAlives: true,
},
}
if resp, err := client.Do(req); err != nil {
t.Error(err)
} else if resp.StatusCode != status {
t.Error(resp.StatusCode)
} else if body, err := ioutil.ReadAll(resp.Body); err != nil {
t.Error(err)
} else if string(body) != result {
t.Error(string(body))
}
}
func TestResponse(t *testing.T) {
m := http.NewServeMux()
m.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello World!\r\n"))
})
m.HandleFunc("/chunked", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Transfer-Encoding", "chunked")
w.Write([]byte("Hello"))
w.Write([]byte(" World!\r\n"))
})
addr := ":8080"
ln, err := net.Listen("tcp", addr)
if err != nil {
t.Error(err)
}
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
for {
conn, err := ln.Accept()
if err != nil {
break
}
go func(conn net.Conn) {
reader := bufio.NewReader(conn)
writer := bufio.NewWriter(conn)
var err error
var req *http.Request
for err == nil {
req, err = ReadFastRequest(reader)
if err != nil {
break
}
res := response.NewResponse(req, conn, bufio.NewReadWriter(reader, writer))
m.ServeHTTP(res, req)
res.FinishRequest()
FreeRequest(req)
response.FreeResponse(res)
}
}(conn)
}
}()
time.Sleep(time.Millisecond * 10)
testHTTP("GET", "http://"+addr+"/", http.StatusOK, "Hello World!\r\n", t)
testHTTP("GET", "http://"+addr+"/chunked", http.StatusOK, "Hello World!\r\n", t)
ln.Close()
wg.Wait()
}
func TestFreeRequest(t *testing.T) {
FreeRequest(nil)
}
func TestFreeHeader(t *testing.T) {
freeHeader(nil)
h := make(http.Header)
h.Add("Content-Type", "text/plain; charset=utf-8")
freeHeader(h)
}