Golang implements requests Library

Keywords: Go JSON github Python

Simple package, convenient to use, like python's requests library.

Github address

Github

Support

  • GET,POST,PUT,DELETE
  • application/json,application/x-www-form-urlencoded

I won't support it:

  • multipart/form-data

Use

The following are common examples: GET request; POST form submission, json submission, saving files, etc.

Get

func getText() {
    text, err := requests.Get("http://127.0.0.1:8080/ping").
        Params(url.Values{
            "param1": {"value1"},
            "param2": {"123"},
        }).
        Send().
        Text()
    if err != nil {
        panic(err)
    }
    fmt.Println(text)
}

Generally, the GET request needs to pass query string, as follows:

GET http://127.0.0.1:8080/ping?param1=value1&param2=123 HTTP/1.1

Post Form

func postForm() {
    text, err := requests.Post("http://127.0.0.1:8080/ping").
        Params(url.Values{
            "param1": {"value1"},
            "param2": {"123"},
        }).
        Form(url.Values{
            "form1": {"value1"},
            "form2": {"123"},
        }).
        Send().
        Text()
    if err != nil {
        panic(err)
    }
    fmt.Println(text)
}

To submit a POST form, you need to put the form parameters in the request body:

POST http://127.0.0.1:8080/ping?param1=value1&param2=123 HTTP/1.1
Content-Type: application/x-www-form-urlencoded

form1=value1&form2=123

Post Json

func postJson() {
    text, err := requests.Post("http://127.0.0.1:8080/ping").
        Params(url.Values{
            "param1": {"value1"},
            "param2": {"123"},
        }).
        Json(map[string]interface{}{
            "json1": "value1",
            "json2": 2,
        }).
        Send().
        Text()
    if err != nil {
        panic(err)
    }
    fmt.Println(text)
}

The POST json request needs to put the json string in the request body:

POST http://127.0.0.1:8080/ping?param1=value1&param2=123 HTTP/1.1
Content-Type: application/json

{"json1": "value1", "json2": 2}

Save file

func save() {
    err := requests.Get("https://github.com/xuanbo/requests").
        Send().
        Save("./requests.html")
    if err != nil {
        panic(err)
    }
}

Implementation ideas

It mainly sends the request through the standard library http of golang. The following is the pseudo code:

// 1. Create request
req, err := http.NewRequest(method, url, strings.NewReader(body))

// 2. Set request header
req.Header

// 3. Send request
resp, err:= http.DefaultClient.Do(req)

// 4. Handling response
r.Resp.Body

Explain

Just for fun!

Posted by JamesyBHOY on Fri, 29 Nov 2019 13:23:41 -0800