-
Notifications
You must be signed in to change notification settings - Fork 0
/
fasthttp.go
124 lines (97 loc) · 2.47 KB
/
fasthttp.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
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
package fasthttp
import (
"context"
"net"
"net/http"
"testing"
"time"
nano_http "github.com/nano-interactive/go-utils/v2/testing/http"
"github.com/valyala/fasthttp/fasthttputil"
"github.com/valyala/fasthttp"
)
type Sender[T any] struct {
dialer func() (net.Conn, error)
testing testing.TB
followRedirect bool
}
func NewWithServer[T any](t testing.TB, s *fasthttp.Server, followRedirects ...bool) *Sender[T] {
t.Helper()
ln := fasthttputil.NewInmemoryListener()
go func() {
if err := s.Serve(ln); err != nil {
t.Error(err)
t.FailNow()
}
}()
t.Cleanup(func() {
if err := ln.Close(); err != nil {
t.Errorf("Failed to close FastHTTP Server")
}
})
return New[T](t, ln.Dial, followRedirects...)
}
func New[T any](t testing.TB, dialer func() (net.Conn, error), followRedirects ...bool) *Sender[T] {
t.Helper()
var followRedirect bool
if len(followRedirects) > 0 {
followRedirect = followRedirects[0]
}
sender := &Sender[T]{
dialer: dialer,
testing: t,
followRedirect: followRedirect,
}
return sender
}
// Sends a HTTP request for testing purposes
func (s *Sender[T]) Test(req *http.Request, timeout ...time.Duration) nano_http.ExtendedResponse[T] {
var tmout time.Duration
if len(timeout) > 0 {
tmout = timeout[0]
}
client := &http.Client{
Transport: &http.Transport{
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
return s.dialer()
},
DialTLSContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
return s.dialer()
},
DisableKeepAlives: true,
DisableCompression: true,
MaxIdleConns: 1,
},
Timeout: tmout,
}
if !s.followRedirect {
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}
}
res, err := client.Do(req)
if err != nil {
s.testing.Errorf("failed to send request: %v", err)
s.testing.FailNow()
}
return nano_http.ExtendedResponse[T]{Response: res}
}
func QueryArgsFromUrl(url string) *fasthttp.Args {
args := &fasthttp.Args{}
args.Parse(url)
return args
}
func CallHandler(t testing.TB, url string, h fasthttp.RequestHandler) *fasthttp.RequestCtx {
t.Helper()
u := fasthttp.URI{}
u.Update(url)
fastHttpCtx := &fasthttp.RequestCtx{
Request: fasthttp.Request{
Header: fasthttp.RequestHeader{},
UseHostHeader: false,
},
Response: fasthttp.Response{},
}
fastHttpCtx.Request.SetURI(&u)
h(fastHttpCtx)
return fastHttpCtx
}