Add http client

This commit is contained in:
Sangeeth Sudheer 2024-05-04 21:27:40 +05:30
parent 6b17bec30c
commit 4e623989ea
Signed by: x
GPG Key ID: F6D06ECE734C57D1
2 changed files with 60 additions and 2 deletions

56
httpclient/httpclient.go Normal file
View File

@ -0,0 +1,56 @@
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)
}
}

View File

@ -45,7 +45,8 @@ import (
// "git.sangeeth.dev/gobyexample/cli" // "git.sangeeth.dev/gobyexample/cli"
// "git.sangeeth.dev/gobyexample/subcmd" // "git.sangeeth.dev/gobyexample/subcmd"
// "git.sangeeth.dev/gobyexample/env" // "git.sangeeth.dev/gobyexample/env"
"git.sangeeth.dev/gobyexample/logging" // "git.sangeeth.dev/gobyexample/logging"
"git.sangeeth.dev/gobyexample/httpclient"
) )
func main() { func main() {
@ -93,5 +94,6 @@ func main() {
// cli.Cli() // cli.Cli()
// subcmd.SubCmd() // subcmd.SubCmd()
// env.Env() // env.Env()
logging.Logging() // logging.Logging()
httpclient.HttpClient()
} }