package main import ( "fmt" "net/http" "io/ioutil" ) func main() { url := "https://jsonplaceholder.typicode.com/posts" req, err := http.NewRequest("GET", url, nil) if err != nil { panic(err) } client := &http.Client{} resp, err := client.Do(req) if err != nil { panic(err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { panic(err) } fmt.Println("Response Body:", string(body)) }
package main import ( "bytes" "encoding/json" "fmt" "net/http" ) type Post struct { UserId int `json:"userId"` Id int `json:"id"` Title string `json:"title"` Body string `json:"body"` } func main() { url := "https://jsonplaceholder.typicode.com/posts" post := Post{UserId: 1, Id: 1, Title: "New post", Body: "This is a new post."} jsonPayload, _ := json.Marshal(post) req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonPayload)) if err != nil { panic(err) } req.Header.Set("Content-Type", "application/json") client := &http.Client{} resp, err := client.Do(req) if err != nil { panic(err) } fmt.Println("Response Status: ", resp.Status) }In this example, a new request is created with the method "POST" and the URL "https://jsonplaceholder.typicode.com/posts". A Post struct is created with some example data, and then encoded into a JSON payload using the json.Marshal function. The request is then executed with the client.Do method, and the response status is printed out. Overall, Go http Request is a powerful package library for handling HTTP requests and responses in Go, and is widely used in web development and APIs.