-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHTTPrequest.go
More file actions
49 lines (40 loc) · 929 Bytes
/
Copy pathHTTPrequest.go
File metadata and controls
49 lines (40 loc) · 929 Bytes
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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
type Post struct {
UserID int `json:"userId"`
ID int `json:"id"`
Title string `json:"title"`
Body string `json:"body"`
}
func main() {
var postID int
fmt.Print("Enter the Post ID: ")
fmt.Scan(&postID)
url := fmt.Sprintf("https://jsonplaceholder.typicode.com/posts/%d", postID)
response, err := http.Get(url)
if err != nil {
fmt.Printf("HTTP GET request failed: %s\n", err)
return
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Printf("Failed to read response body: %s\n", err)
return
}
var post Post
err = json.Unmarshal(body, &post)
if err != nil {
fmt.Printf("Failed to parse JSON: %s\n", err)
return
}
fmt.Printf("UserID: %d\n", post.UserID)
fmt.Printf("ID: %d\n", post.ID)
fmt.Printf("Title: %s\n", post.Title)
fmt.Printf("Body: %s\n", post.Body)
}