resp, err := http.Get("http://example.com/") if err != nil { // handle error } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { // handle error } fmt.Println(string(body))
data := url.Values{} data.Set("username", "myusername") data.Set("password", "mypassword") resp, err := http.PostForm("https://example.com/login", data) if err != nil { // handle error } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { // handle error } fmt.Println(string(body))
client := &http.Client{ Timeout: time.Second * 10, } req, err := http.NewRequest("GET", "https://example.com/", nil) if err != nil { // handle error } resp, err := client.Do(req) if err != nil { // handle error } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { // handle error } fmt.Println(string(body))In this example, we create a custom `http.Client` with a 10 second timeout. We then create an `http.Request` object with a GET method and the URL `https://example.com/`, and use the custom client to send the request. We handle errors, defer the closing of the response body, read its contents into a byte slice, and print the response. All of these examples use the `net/http` package in Go. This package provides a wide range of functions and methods for making HTTP requests, handling responses, and customizing network clients. Overall, the `net/http` package is a crucial library for building robust network clients in Go.