Add http client
This commit is contained in:
parent
6b17bec30c
commit
4e623989ea
56
httpclient/httpclient.go
Normal file
56
httpclient/httpclient.go
Normal 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)
|
||||||
|
}
|
||||||
|
}
|
6
main.go
6
main.go
@ -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()
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user