-
-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathhandler_example_test.go
95 lines (90 loc) · 1.88 KB
/
handler_example_test.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
package requests_test
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"strings"
"github.com/carlmjohnson/requests"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
func ExampleToBufioReader() {
// read a response line by line for a sentinel
found := false
err := requests.
URL("http://example.com").
Handle(requests.ToBufioReader(func(r *bufio.Reader) error {
var err error
for s := ""; err == nil; {
if strings.Contains(s, "Example Domain") {
found = true
return nil
}
// read one line from response
s, err = r.ReadString('\n')
}
if err == io.EOF {
return nil
}
return err
})).
Fetch(context.Background())
if err != nil {
fmt.Println("could not connect to example.com:", err)
}
fmt.Println(found)
// Output:
// true
}
func ExampleToBufioScanner() {
// read a response line by line for a sentinel
found := false
needle := []byte("Example Domain")
err := requests.
URL("http://example.com").
Handle(requests.ToBufioScanner(func(s *bufio.Scanner) error {
// read one line at time from response
for s.Scan() {
if bytes.Contains(s.Bytes(), needle) {
found = true
return nil
}
}
return s.Err()
})).
Fetch(context.Background())
if err != nil {
fmt.Println("could not connect to example.com:", err)
}
fmt.Println(found)
// Output:
// true
}
func ExampleToHTML() {
var doc html.Node
err := requests.
URL("http://example.com").
Handle(requests.ToHTML(&doc)).
Fetch(context.Background())
if err != nil {
fmt.Println("could not connect to example.com:", err)
}
var f func(*html.Node)
f = func(n *html.Node) {
if n.DataAtom == atom.A {
for _, attr := range n.Attr {
if attr.Key == "href" {
fmt.Println("link:", attr.Val)
}
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
f(c)
}
}
f(&doc)
// Output:
// link: https://www.iana.org/domains/example
}