-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
78 lines (56 loc) · 1.46 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
package main
import (
"fmt"
"io"
"net/http"
"net/url"
"strings"
)
const basePath = "https://jsonplaceholder.typicode.com/posts/"
func main() {
fmt.Println("More about http requests in go")
// MakeGetRequest()
// MakePostRequest()
MakePostRequestWithFormData()
}
func MakeGetRequest() {
response, err := http.Get(basePath + "1")
if err != nil {
panic(err)
}
defer response.Body.Close()
contentBytes, _ := io.ReadAll(response.Body)
posts := string(contentBytes)
fmt.Println("Post:", posts)
}
func MakePostRequest() {
requestBody := strings.NewReader(`
{
"userId":1,
"title":"I just made a new post",
"body":"Such a long, long time ago. There existed some code which never worked"
}
`)
response, err := http.Post(basePath, "application/json", requestBody)
if err != nil {
panic(err)
}
defer response.Body.Close()
contentBytes, _ := io.ReadAll(response.Body)
post := string(contentBytes)
fmt.Println("Created a post:", post)
}
func MakePostRequestWithFormData() {
requestBody := url.Values{}
requestBody.Add("userId", "1")
requestBody.Add("title", "I just made a new post")
requestBody.Add("body", "Such a long, long time ago. There existed some code which never worked")
response, err := http.PostForm(basePath, requestBody)
if err != nil {
panic(err)
}
defer response.Body.Close()
contentBytes, _ := io.ReadAll(response.Body)
post := string(contentBytes)
fmt.Println("Created a post using url encoded form:", post)
}