-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
64 lines (57 loc) · 1.37 KB
/
main.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
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
aux "github.com/allaman/toolbox/http-client/auxiliary"
)
var (
baseURL = "https://postman-echo.com"
c = http.Client{Timeout: time.Duration(1) * time.Second}
)
func main() {
cookies := get("/get?foo1=bar1&foo2=bar2")
post("/post", map[string]string{"foo": "bar"}, cookies)
}
func get(path string) []*http.Cookie {
resp, err := c.Get(fmt.Sprintf("%s%s", baseURL, path))
if err != nil {
panic(err)
}
defer resp.Body.Close()
for _, cookie := range resp.Cookies() {
fmt.Printf("Found a cookie named '%s' with value '%s'\n", cookie.Name, cookie.Value)
}
return resp.Cookies()
}
func post(path string, body interface{}, cookies []*http.Cookie) {
jsonData, err := json.Marshal(body)
if err != nil {
panic(err)
}
req, err := http.NewRequest("POST", fmt.Sprintf("%s%s", baseURL, path), bytes.NewBuffer((jsonData)))
if err != nil {
panic(err)
}
req.Header.Set("Content-Type", "application/json; charset=UTF-8")
for i := range cookies {
req.AddCookie(cookies[i])
}
fmt.Println("Posting with cookie...")
resp, err := c.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println("Result with posted cookie")
aux.PrintResponse(resp)
}
// Read converts a io.Reader object to a string
func read(r io.Reader) string {
var b bytes.Buffer
b.ReadFrom(r)
return b.String()
}