gobyexample/httpclient/httpclient.go

57 lines
842 B
Go
Raw Normal View History

2024-05-04 15:57:40 +00:00
package httpclient
import (
"encoding/json"
"fmt"
"io"
"net/http"
)
func HttpClient() {
GetHtml()
GetJson()
}
func GetHtml() {
resp, err := http.Get("https://example.com")
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println("status:", resp.StatusCode)
rawData, err := io.ReadAll(resp.Body)
if err != nil {
panic(err)
}
fmt.Println("Raw html response:")
fmt.Println(string(rawData))
}
type User struct {
Id int `json:"id"`
Name string `json:"name"`
}
func GetJson() {
resp, err := http.Get("https://jsonplaceholder.typicode.com/users")
if err != nil {
panic(err)
}
defer resp.Body.Close()
var users []User
dec := json.NewDecoder(resp.Body)
err = dec.Decode(&users)
if err != nil {
panic(err)
}
for _, user := range users {
fmt.Println("id:", user.Id, "name:", user.Name)
}
}