/
intercept.go
41 lines (34 loc) · 935 Bytes
/
intercept.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
package main
import (
"fmt"
"gopkg.in/h2non/gentleman.v2"
"gopkg.in/h2non/gentleman.v2/context"
"gopkg.in/h2non/gentleman.v2/utils"
)
func main() {
// Create a new client
cli := gentleman.New()
// Creates a new request based on the current client
req := cli.Request().URL("http://httpbin.org/get")
// Attach a request midddleware function to intercept the request.
req.UseRequest(func(ctx *context.Context, h context.Handler) {
// If host matches, intercept the request
if ctx.Request.URL.Host == "httpbin.org" {
ctx.Response.StatusCode = 200
utils.WriteBodyString(ctx.Response, "intercepted\n")
}
h.Stop(ctx)
})
// Perform the request
res, err := req.Send()
if err != nil {
fmt.Printf("Request error: %s\n", err)
return
}
if !res.Ok {
fmt.Printf("Invalid server response: %d\n", res.StatusCode)
return
}
fmt.Printf("Status: %d\n", res.StatusCode)
fmt.Printf("Body: %s", res.String())
}