-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
59 lines (42 loc) · 1.08 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
package main
import (
"fmt"
"io"
"net/http"
"os"
)
const baseUrl = "https://jsonplaceholder.typicode.com/"
func main() {
fmt.Println("Http requests in Golang")
fmt.Println("Making an http request to:", baseUrl)
response, err := http.Get(baseUrl + "posts")
if err != nil {
panic(err)
}
defer response.Body.Close() // Closing http requests should be done manually
fmt.Println("Reading response body")
posts, err := io.ReadAll(response.Body)
if err != nil {
panic(err)
}
content := string(posts)
fmt.Println("Retrieved posts from remote server:", content)
fmt.Println("What do you want to name your name:")
var fileName string
fmt.Scanln(&fileName)
fileName = "./" + fileName + ".json"
file, err := os.Create(fileName)
if err != nil {
panic(err)
}
defer file.Close()
writeFile(file, content)
fmt.Printf("Created file %v and wrote posts in that.\n", fileName)
}
func writeFile(file *os.File, stringToWrite string) {
length, err := io.WriteString(file, stringToWrite)
if err != nil {
panic(err)
}
fmt.Println("The length written to file is:", length)
}