HTTP Client
net/http
package in go can be used to send request to other http servers (similar to fetch in JS)
Sending a request
Write a function sendRequest
that gets the post details from https://jsonplaceholder.typicode.com/posts/1
package main
import ( "encoding/json" "fmt" "io" "net/http")
type post struct { UserId int `json:"userId"` Id int `json:"id"` Title string `json:"title"` Body string `json:"body"`}
func sendRequest(url string, ch chan string) { resp, error := http.Get(url)
if error != nil { ch <- "Error while sending request" }
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil { ch <- "Error while reading body" }
p := post{}
json.Unmarshal(body, &p)
ch <- p.Title}
func main() { ch := make(chan string) go sendRequest("https://jsonplaceholder.typicode.com/posts/1", ch) ans := <-ch fmt.Print(ans)}