Skip to content

Commit 888d7fd

Browse files
authored
Try http requests
1 parent 49a0087 commit 888d7fd

File tree

3 files changed

+82
-0
lines changed

3 files changed

+82
-0
lines changed

httpGet.go

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package main
2+
3+
import (
4+
"io/ioutil"
5+
"log"
6+
"net/http"
7+
)
8+
9+
func main() {
10+
resp, err := http.Get("https://httpbin.org/get")
11+
if err != nil {
12+
log.Fatalln(err)
13+
}
14+
15+
defer resp.Body.Close()
16+
17+
body, err := ioutil.ReadAll(resp.Body)
18+
if err != nil {
19+
log.Fatalln(err)
20+
}
21+
22+
log.Println(string(body))
23+
}

httpPost.go

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package main
2+
3+
import (
4+
"bytes"
5+
"encoding/json"
6+
"io/ioutil"
7+
"log"
8+
"net/http"
9+
)
10+
11+
func main() {
12+
reqBody, err := json.Marshal(map[string]string{
13+
"name": "Ivanov Ivan",
14+
"email": "[email protected]",
15+
})
16+
17+
if err != nil {
18+
log.Fatalln(err)
19+
}
20+
21+
resp, err := http.Post("https://httpbin.org/post", "application/json", bytes.NewBuffer(reqBody))
22+
if err != nil {
23+
log.Fatalln(err)
24+
}
25+
26+
defer resp.Body.Close()
27+
28+
body, err := ioutil.ReadAll(resp.Body)
29+
if err != nil {
30+
log.Fatalln(err)
31+
}
32+
33+
log.Println(string(body))
34+
}

httpPostForm.go

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package main
2+
3+
import (
4+
"encoding/json"
5+
"log"
6+
"net/http"
7+
"net/url"
8+
)
9+
10+
func main() {
11+
formData := url.Values{
12+
"name": {"Ivan"},
13+
}
14+
15+
resp, err := http.PostForm("https://httpbin.org/post", formData)
16+
if err != nil {
17+
log.Fatalln(err)
18+
}
19+
20+
var result map[string]interface{}
21+
22+
json.NewDecoder(resp.Body).Decode(&result)
23+
24+
log.Println(result["form"])
25+
}

0 commit comments

Comments
 (0)