From 4e623989ea7103c062cbf557d05e25565794a873 Mon Sep 17 00:00:00 2001 From: Sangeeth Sudheer Date: Sat, 4 May 2024 21:27:40 +0530 Subject: [PATCH] Add http client --- httpclient/httpclient.go | 56 ++++++++++++++++++++++++++++++++++++++++ main.go | 6 +++-- 2 files changed, 60 insertions(+), 2 deletions(-) create mode 100644 httpclient/httpclient.go diff --git a/httpclient/httpclient.go b/httpclient/httpclient.go new file mode 100644 index 0000000..9d607e7 --- /dev/null +++ b/httpclient/httpclient.go @@ -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) + } +} diff --git a/main.go b/main.go index 36e02aa..6eea9fd 100644 --- a/main.go +++ b/main.go @@ -45,7 +45,8 @@ import ( // "git.sangeeth.dev/gobyexample/cli" // "git.sangeeth.dev/gobyexample/subcmd" // "git.sangeeth.dev/gobyexample/env" - "git.sangeeth.dev/gobyexample/logging" + // "git.sangeeth.dev/gobyexample/logging" + "git.sangeeth.dev/gobyexample/httpclient" ) func main() { @@ -93,5 +94,6 @@ func main() { // cli.Cli() // subcmd.SubCmd() // env.Env() - logging.Logging() + // logging.Logging() + httpclient.HttpClient() }