-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathbuilder.go
More file actions
369 lines (315 loc) · 14 KB
/
Copy pathbuilder.go
File metadata and controls
369 lines (315 loc) · 14 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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
package surf
import (
"context"
"crypto/tls"
"fmt"
"time"
"github.com/enetx/g"
"github.com/enetx/http"
"github.com/enetx/surf/profiles"
)
// Builder provides a fluent interface for configuring HTTP clients with various advanced features
// including proxy settings, TLS fingerprinting, HTTP/2 and HTTP/3 support, retry logic,
// redirect handling, and browser impersonation capabilities.
type Builder struct {
retryCodes g.Slice[int] // HTTP status codes that trigger retries
proxy g.String // Proxy URL for client connections
cli *Client // The client being configured
checkRedirect func(*http.Request, []*http.Request) error // Custom redirect policy function
http2settings *HTTP2Settings // HTTP/2 specific settings
http3settings *HTTP3Settings // HTTP/3 specific settings
cliMWs *middleware[*Client] // Priority-ordered client middlewares
headersApplier profiles.HeadersApplier // Profile-specific request header pipeline (set by Impersonate)
retryWait time.Duration // Wait duration between retry attempts
retryMax int // Maximum number of retry attempts
maxRedirects int // Maximum number of redirects to follow
forceHTTP1 bool // Force HTTP/1.1 protocol usage
forceHTTP2 bool // Force HTTP/2 protocol usage
forceHTTP3 bool // Force HTTP/3 protocol usage
cacheBody bool // Enable response body caching
followOnlyHostRedirects bool // Only follow redirects within same host
forwardHeadersOnRedirect bool // Preserve headers during redirects
ja bool // Enable JA3 TLS fingerprinting
disableCompression bool // Disable automatic response body decompression
}
// Build applies all configured settings and returns the client.
// Returns g.Result with error if any middleware fails.
func (b *Builder) Build() g.Result[*Client] {
if err := b.cliMWs.run(b.cli); err != nil {
return g.Err[*Client](err)
}
return g.Ok(b.cli)
}
// With registers middleware into the client builder with optional priority.
//
// It accepts one of the following middleware function types:
// - func(*surf.Client) error — client middleware, modifies or initializes the client
// - func(*surf.Request) error — request middleware, intercepts or transforms outgoing requests
// - func(*surf.Response) error — response middleware, intercepts or transforms incoming responses
//
// Parameters:
// - middleware: A function matching one of the supported middleware types.
// - priority (optional): Integer priority level. Lower values run earlier. Defaults to 0.
//
// Middleware with the same priority are executed in order of insertion (FIFO).
// If the middleware type is not recognized, With panics with an informative error.
//
// Example:
//
// // Adding client middleware to modify client settings.
// .With(func(client *surf.Client) error {
// // Custom logic to modify the client settings.
// return nil
// })
//
// // Adding request middleware to intercept outgoing requests.
// .With(func(req *surf.Request) error {
// // Custom logic to modify outgoing requests.
// return nil
// })
//
// // Adding response middleware to intercept incoming responses.
// .With(func(resp *surf.Response) error {
// // Custom logic to handle incoming responses.
// return nil
// })
//
// Note: Ensure that middleware functions adhere to the specified function signatures to work correctly with the With method.
func (b *Builder) With(middleware any, priority ...int) *Builder {
p := g.Int(g.Slice[int](priority).Get(0).UnwrapOrDefault())
switch v := middleware.(type) {
case func(*Client) error:
b.addCliMW(v, p)
case func(*Request) error:
b.addReqMW(v, p)
case func(*Response) error:
b.addRespMW(v, p)
default:
panic(fmt.Sprintf("invalid middleware type: %T", v))
}
return b
}
// addCliMW adds a client middleware to the ClientBuilder.
func (b *Builder) addCliMW(m func(*Client) error, priority g.Int) *Builder {
b.cliMWs.add(priority, m)
return b
}
// addReqMW adds a request middleware to the ClientBuilder.
func (b *Builder) addReqMW(m func(*Request) error, priority g.Int) *Builder {
b.cli.reqMWs.add(priority, m)
return b
}
// addRespMW adds a response middleware to the ClientBuilder.
func (b *Builder) addRespMW(m func(*Response) error, priority g.Int) *Builder {
b.cli.respMWs.add(priority, m)
return b
}
func (b *Builder) Boundary(boundary func() g.String) *Builder {
return b.addCliMW(func(client *Client) error { return boundaryMW(client, boundary) }, 999)
}
// SecureTLS enables TLS certificate verification.
// By default surf skips certificate verification (InsecureSkipVerify=true).
// Call this for production use where certificate validation is required.
func (b *Builder) SecureTLS() *Builder {
b.cli.tlsConfig.InsecureSkipVerify = false
return b
}
// WebSocketGuard enables middleware that blocks WebSocket upgrade responses (HTTP 101).
// Without this, surf allows 101 Switching Protocols to pass through — compatible with
// websocket.Dial and other WebSocket libraries that use surf.Std() as HTTPClient.
// Enable this only if you want to explicitly reject unexpected WebSocket upgrades.
func (b *Builder) WebSocketGuard() *Builder {
b.addReqMW(got101ResponseMW, 0)
b.addRespMW(webSocketUpgradeErrorMW, 0)
return b
}
// H2C configures the client to handle HTTP/2 Cleartext (h2c).
func (b *Builder) H2C() *Builder { return b.addCliMW(h2cMW, 999) }
// HTTP2Settings configures settings related to HTTP/2 and returns an http2s struct.
func (b *Builder) HTTP2Settings() *HTTP2Settings {
h2 := &HTTP2Settings{builder: b}
b.http2settings = h2
return h2
}
// HTTP3Settings configures settings related to HTTP/3 and returns an http3s struct.
func (b *Builder) HTTP3Settings() *HTTP3Settings {
h3 := &HTTP3Settings{builder: b}
b.http3settings = h3
return h3
}
// ForceHTTP3 configures the client to use HTTP/3 forcefully.
func (b *Builder) ForceHTTP3() *Builder {
b.forceHTTP3 = true
return b
}
// Impersonate configures something related to impersonation and returns an impersonate struct.
func (b *Builder) Impersonate() *Impersonate { return &Impersonate{builder: b} }
// JA configures the client to use a specific TLS fingerprint.
func (b *Builder) JA() *JA {
b.ja = true
return &JA{builder: b}
}
// UnixSocket sets the path for a Unix domain socket.
// This allows the HTTP client to connect to the server using a Unix domain
// socket instead of a traditional TCP/IP connection.
func (b *Builder) UnixSocket(address g.String) *Builder {
return b.addCliMW(func(client *Client) error { return unixSocketMW(client, address) }, 0)
}
// DNS sets the custom DNS resolver address.
func (b *Builder) DNS(dns g.String) *Builder {
return b.addCliMW(func(client *Client) error { return dnsMW(client, dns) }, 0)
}
// DNSOverTLS configures the client to use DNS over TLS.
func (b *Builder) DNSOverTLS() *DNSOverTLS { return &DNSOverTLS{builder: b} }
// Timeout sets the timeout duration for the client.
func (b *Builder) Timeout(timeout time.Duration) *Builder {
return b.addCliMW(func(client *Client) error { return timeoutMW(client, timeout) }, 0)
}
// TLSConfig sets a custom TLS configuration for the client.
func (b *Builder) TLSConfig(config *tls.Config) *Builder {
return b.addCliMW(func(client *Client) error { return tlsConfigMW(client, config) }, 0)
}
// InterfaceAddr sets the local network interface for outbound connections.
// Accepts either an IP address (e.g., "192.168.1.100", "::1") or an interface name (e.g., "eth0", "en0").
func (b *Builder) InterfaceAddr(address g.String) *Builder {
return b.addCliMW(func(client *Client) error { return interfaceAddrMW(client, address) }, 0)
}
// Proxy sets the proxy URL for the client.
func (b *Builder) Proxy(proxy g.String) *Builder {
b.proxy = proxy
return b.addCliMW(func(client *Client) error { return proxyMW(client, proxy) }, 0)
}
// BasicAuth sets the basic authentication credentials for the client.
func (b *Builder) BasicAuth(authentication g.String) *Builder {
return b.addReqMW(func(req *Request) error { return basicAuthMW(req, authentication) }, 900)
}
// BearerAuth sets the bearer token for the client.
func (b *Builder) BearerAuth(authentication g.String) *Builder {
return b.addReqMW(func(req *Request) error { return bearerAuthMW(req, authentication) }, 901)
}
// UserAgent sets the user agent for the client.
func (b *Builder) UserAgent(userAgent any) *Builder {
return b.addReqMW(func(req *Request) error { return userAgentMW(req, userAgent) }, 0)
}
// SetHeaders sets headers for the request, replacing existing ones with the same name.
func (b *Builder) SetHeaders(headers ...any) *Builder {
return b.addReqMW(func(r *Request) error {
r.SetHeaders(headers...)
return nil
}, 0)
}
// AddHeaders adds headers to the request, appending to any existing headers with the same name.
func (b *Builder) AddHeaders(headers ...any) *Builder {
return b.addReqMW(func(r *Request) error {
r.AddHeaders(headers...)
return nil
}, 0)
}
// AddCookies adds cookies to the request.
func (b *Builder) AddCookies(cookies ...*http.Cookie) *Builder {
return b.addReqMW(func(r *Request) error {
r.AddCookies(cookies...)
return nil
}, 0)
}
// WithContext associates the provided context with the request.
func (b *Builder) WithContext(ctx context.Context) *Builder {
return b.addReqMW(func(r *Request) error {
r.WithContext(ctx)
return nil
}, 0)
}
// ContentType sets the content type for the client.
func (b *Builder) ContentType(contentType g.String) *Builder {
return b.addReqMW(func(req *Request) error { return contentTypeMW(req, contentType) }, 0)
}
// CacheBody configures whether the client should cache the body of the response.
func (b *Builder) CacheBody() *Builder {
b.cacheBody = true
return b
}
// GetRemoteAddress configures whether the client should get the remote address.
func (b *Builder) GetRemoteAddress() *Builder { return b.addReqMW(remoteAddrMW, 0) }
// DisableKeepAlive disable keep-alive connections.
func (b *Builder) DisableKeepAlive() *Builder { return b.addCliMW(disableKeepAliveMW, 0) }
// DisableCompression disables automatic response body decompression.
func (b *Builder) DisableCompression() *Builder {
b.disableCompression = true
return b
}
// Retry configures the retry behavior of the client.
//
// Parameters:
//
// retryMax: Maximum number of retry attempts. If zero or negative the
// retry loop is disabled.
// retryWait: Minimum wait between retries. If the server responds with a
// Retry-After header on a retryable status, the actual pause
// becomes max(retryWait, Retry-After). Both legal forms are
// honoured: integer delay-seconds and HTTP-date (IMF-fixdate,
// RFC 850, ANSI C asctime). Absent or malformed values fall
// back to retryWait.
// codes: Optional list of HTTP status codes that trigger retries.
// If no codes are provided, the defaults are used
// (500 Internal Server Error, 429 Too Many Requests,
// 503 Service Unavailable).
//
// Upper bound for the entire retry cycle, including a long Retry-After
// sleep, is the request context deadline — set it with
// Request.WithContext(ctxWithDeadline). Builder.Timeout only bounds a
// single cli.Do invocation (connect + transmission + body read); it does
// not interrupt the sleep between retries.
func (b *Builder) Retry(retryMax int, retryWait time.Duration, codes ...int) *Builder {
b.retryMax = retryMax
b.retryWait = retryWait
if len(codes) == 0 {
b.retryCodes = g.SliceOf(
http.StatusInternalServerError,
http.StatusTooManyRequests,
http.StatusServiceUnavailable,
)
} else {
b.retryCodes = g.SliceOf(codes...)
}
return b
}
// ForceHTTP1 configures the client to use HTTP/1.1 forcefully.
func (b *Builder) ForceHTTP1() *Builder {
b.forceHTTP1 = true
return b.addCliMW(forceHTTP1MW, 0)
}
// ForceHTTP2 configures the client to use HTTP/2 forcefully.
func (b *Builder) ForceHTTP2() *Builder {
b.forceHTTP2 = true
return b.addCliMW(forceHTTP2MW, 0)
}
// Session configures whether the client should maintain a session.
func (b *Builder) Session() *Builder { return b.addCliMW(sessionMW, 0) }
// MaxRedirects sets the maximum number of redirects the client should follow.
func (b *Builder) MaxRedirects(maxRedirects int) *Builder {
b.maxRedirects = maxRedirects
return b.addCliMW(redirectPolicyMW, 0)
}
// NotFollowRedirects disables following redirects for the client.
func (b *Builder) NotFollowRedirects() *Builder {
return b.RedirectPolicy(func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse })
}
// FollowOnlyHostRedirects configures whether the client should only follow redirects within the
// same host.
func (b *Builder) FollowOnlyHostRedirects() *Builder {
b.followOnlyHostRedirects = true
return b.addCliMW(redirectPolicyMW, 0)
}
// ForwardHeadersOnRedirect adds a middleware to the ClientBuilder object that ensures HTTP headers are
// forwarded during a redirect.
func (b *Builder) ForwardHeadersOnRedirect() *Builder {
b.forwardHeadersOnRedirect = true
return b.addCliMW(redirectPolicyMW, 0)
}
// RedirectPolicy sets a custom redirect policy for the client.
func (b *Builder) RedirectPolicy(fn func(*http.Request, []*http.Request) error) *Builder {
b.checkRedirect = fn
return b.addCliMW(redirectPolicyMW, 0)
}
// String generate a string representation of the ClientBuilder instance.
func (b Builder) String() string { return fmt.Sprintf("%#v", b) }