Golang is a rapidly emerging programming language that has also attracted much attention in network programming. In Golang, network programming can be easily performed by using the http request package. This article will introduce Golang's http request package, including knowledge about sending http requests, receiving http responses, etc.
In Golang, use the http.NewRequest() function to create an http request. The parameters of this function include the request method, URL, request body, etc.
func NewRequest(method, url string, body io.Reader) (*Request, error)
Sample code:
package main import ( "bytes" "fmt" "io/ioutil" "net/http" ) func main() { url := "http://example.com" jsonStr := []byte(`{"name":"John"}`) req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr)) req.Header.Set("Content-Type", "application/json") client := &http.Client{} resp, err := client.Do(req) if err != nil { panic(err) } defer resp.Body.Close() body, _ := ioutil.ReadAll(resp.Body) fmt.Println("response Body:", string(body)) }
In the above code, we use the http.NewRequest() function to create a POST request and set the Content-Type of the request header. Use http.Client{} to send a request and read the response body through the ReadAll() function of the ioutil package.
In Golang, the http.Response structure is used to represent the http response. The structure includes response status code, response header, response body and other information.
type Response struct { Status string StatusCode int Proto string ProtoMajor int ProtoMinor int Header Header Body io.ReadCloser ContentLength int64 TransferEncoding []string Close bool Uncompressed bool Trailer Header Request *Request TLS *tls.ConnectionState Cancel <-chan struct{} }
Sample code:
package main import ( "fmt" "io/ioutil" "net/http" ) func main() { resp, err := http.Get("http://example.com") if err != nil { panic(err) } defer resp.Body.Close() fmt.Println("response Status:", resp.Status) fmt.Println("response Headers:", resp.Header) body, _ := ioutil.ReadAll(resp.Body) fmt.Println("response Body:", string(body)) }
In the above code, we use the http.Get() function to send a GET request and obtain the response status through resp.Status, resp.Header, and resp.Body respectively. code, response header, response body, and output in string form.
Summary
Golang’s http request package provides a very convenient network programming interface, making network programming simple and efficient. We can create http requests through functions such as http.NewRequest() and http.Get(), and obtain http response information through the http.Response structure. Mastering Golang's http request package can improve code reusability and readability when implementing web servers and web services.
The above is the detailed content of An article introducing Golang's http request package. For more information, please follow other related articles on the PHP Chinese website!