-
Notifications
You must be signed in to change notification settings - Fork 0
/
post.go
57 lines (46 loc) · 1.01 KB
/
post.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
package main
import (
"fmt"
"io"
)
func Post(flags *Flags) ([]byte, error) {
// Use SetupRequest() to setup the connection
client, host, path, err := SetupRequest(flags)
if err != nil {
return nil, err
}
// Defer closing the connection
defer client.Close()
// Request Format:
// Protocol / HTTP/ver
// Host
// Headers
// Connection Close/Keep Alive
// Body
req := "POST " + path + " HTTP/1.1\r\n"
req += fmt.Sprintf("Host: %s\r\n", host)
req += fmt.Sprintf("content-length: %d\r\n", len(flags.PostBody))
for _, v := range flags.Headers {
req += fmt.Sprintf("%v\r\n", v)
}
if flags.KeepAlive {
req += "Connection: keep-alive \r\n"
} else {
req += "Connection: close \r\n"
}
req += "\r\n"
// Append body to the request
req += flags.PostBody
req += "\r\n"
// Send the request to the host
_, err = client.Write([]byte(req))
if err != nil {
return nil, err
}
// Read the response and return to the user
res, err := io.ReadAll(client)
if err != nil {
return nil, err
}
return res, nil
}