forked from kataras/iris
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
102 lines (81 loc) · 1.78 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
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
package main
import (
"bytes"
"compress/gzip"
"encoding/json"
"fmt"
"io"
"net/http"
)
var client = http.DefaultClient
const baseURL = "http://localhost:8080"
func main() {
fmt.Printf("Running client example on: %s\n", baseURL)
getExample()
postExample()
}
func getExample() {
endpoint := baseURL + "/"
req, err := http.NewRequest(http.MethodGet, endpoint, nil)
if err != nil {
panic(err)
}
// Required to receive server's compressed data.
req.Header.Set("Accept-Encoding", "gzip")
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
// decompress server's compressed reply.
r, err := gzip.NewReader(resp.Body)
if err != nil {
panic(err)
}
defer r.Close()
body, err := io.ReadAll(r)
if err != nil {
panic(err)
}
fmt.Printf("Received from server: %s", string(body))
}
type payload struct {
Username string `json:"username"`
}
func postExample() {
buf := new(bytes.Buffer)
// Compress client's data.
w := gzip.NewWriter(buf)
b, err := json.Marshal(payload{Username: "Edward"})
if err != nil {
panic(err)
}
w.Write(b)
w.Close()
endpoint := baseURL + "/"
req, err := http.NewRequest(http.MethodPost, endpoint, buf)
if err != nil {
panic(err)
}
req.Header.Set("Content-Type", "application/json")
// Required to send gzip compressed data to the server.
req.Header.Set("Content-Encoding", "gzip")
// Required to receive server's compressed data.
req.Header.Set("Accept-Encoding", "gzip")
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
// Decompress server's compressed reply.
r, err := gzip.NewReader(resp.Body)
if err != nil {
panic(err)
}
defer r.Close()
body, err := io.ReadAll(r)
if err != nil {
panic(err)
}
fmt.Printf("Server replied with: %s", string(body))
}