-
Notifications
You must be signed in to change notification settings - Fork 0
/
requestExample.go
54 lines (41 loc) · 1.05 KB
/
requestExample.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
package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
)
func main() {
url := "https://httpbin.org/post"
data := []byte(`{"hello": "world"}`)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(data))
if err != nil {
log.Fatal("Error reading request. ", err)
}
// Set headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Host", "httpbin.org")
// Create and Add cookie to request
cookie := http.Cookie{Name: "cookie_name", Value: "cookie_value"}
req.AddCookie(&cookie)
// Set client timeout
client := &http.Client{Timeout: time.Second * 10}
// Validate cookie and headers are attached
fmt.Println(req.Cookies())
fmt.Println(req.Header)
// Send request
resp, err := client.Do(req)
if err != nil {
log.Fatal("Error reading response. ", err)
}
defer resp.Body.Close()
fmt.Println("response Status:", resp.Status)
fmt.Println("response Headers:", resp.Header)
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal("Error reading body. ", err)
}
fmt.Printf("%s\n", body)
}