An article introducing Golang's http request package

PHPz
Release: 2023-04-24 15:07:44
Original
866 people have browsed it

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.

  1. Send http request

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)
Copy after login

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))
}
Copy after login

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.

  1. Receive http response

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{}
}
Copy after login

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))
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template