The Golang requests Library is updated with the following methods

Source: Internet
Author: User
Tags auth setcookie

Requests

requestsis a requests library with the Golang language clone python version.
Golang's own net/http function has been very well developed. It is as good as the Urllib series library in Python, but it is cumbersome to use.

Python version of the requests is simply an artifact, so many people are very admired.

So I started to wrap up a requests in the way Python requests thought.

Before I do, I want to be as compatible with Python as possible. But Golang does not support the function name lowercase,
Parameter naming is also not supported. So I can only use the schema of the parameter type to support dynamic parameters.

Installation

Golang 1.11 ago

go get -u github.com/asmcos/requests

Golang after 1.11, edit a Go.mod file

module github.com/asmcos/requests

!!! Special Instructions
Since the requests code is being updated, all examples are currently valid.
And some fragments have context. Please refer to the original code when you read Requests_test.go

Start using (with auth)

package mainimport (        "github.com/asmcos/requests"        "fmt")func main (){        req := requests.Requests()        resp,_ := req.Get("https://api.github.com/user",requests.Auth{"asmcos","password...."})        println(resp.Text())        fmt.Println(resp.R.StatusCode)        fmt.Println(resp.R.Header["Content-Type"])}

The first example is why it? Because the first example of Python requests is it ... Oh

注意::: `密码` 和用户名要用github真实用户才能测试。

How to create a request

Example 1

Minimalist use

package mainimport "github.com/asmcos/requests"func main (){        resp,_ := requests.Get("http://go.xiulian.net.cn")        println(resp.Text())}

In fact, requests implementation is to first use the requests () function to create a request and client,
Then use the Req. Get go to request.

Requests. Get is an encapsulation of requests () and Req. A package for get.

Example 2

This example is divided into 2 steps to operate, and the benefit is that various request parameters can be set through req.
The following example shows various settings.

package mainimport "github.com/asmcos/requests"func main (){        req := requests.Requests()        resp,_ := req.Get("http://go.xiulian.net.cn",requests.Header{"Referer":"http://www.jeapedu.com"})        println(resp.Text())}

Set Header

req := Requests()req.Header.Set("accept-encoding", "gzip, deflate, br")req.Get("http://go.xiulian.net.cn", requests.Header{"Referer": "http://www.jeapedu.com"})

!!! 2 ways to set up your head
1. Through req. Header.set function directly set
2. Call req. Get function, fill in the function parameters.

Get supports dynamic parameters, but the parameters are preceded by type identification.

The function inside determines the meaning of the parameter according to the type.

In fact, the parameters of the function can be set more than once on the header parameter.

url1 := "http://go.xiulian.net.cn"req.Get(url1, requests.Header{"k0": "v0"},requests.Header{"k1":"v1"},requests.Header{"k2":"v2"})h := requests.Header{  "k3":"v3",  "k4":"v4",  "k5":"v5",}req.Get(url1,h)

These are all possible. Flexibility to add head.

Setting parameters

p := requests.Params{  "title": "The blog",  "name":  "file",  "id":    "12345",}resp,_ := Requests().Get("http://www.cpython.org", p)

In fact the parameter setting. The parameter settings are also supported multiple times.

Similar to the following:

resp,_ := Requests().Get("http://www.cpython.org", p,p1,p2)

Form form for POST

data := Datas{    "comments": "ew",    "custemail": "a@231.com",    "custname": "1",    "custtel": "2",    "delivery": "12:45",    "size": "small",    "topping": "bacon",  }resp,_ := req.Post("https://www.httpbin.org/post",data)fmt.Println(resp.Text())

!!!! 注意The Post form is placed inside the body, and the get params is placed inside the URL.

Proxy

Agents with password authentication are not currently supported.

req = Requests()req.Proxy("http://192.168.1.190:8888")resp,_ = req.Get("https://www.sina.com.cn")

Set cookies

Requests supports its own delivery of cookies. Essentially, cookies exist inside Client.jar.
User-Set cookies are also passed along with Client.jar.

req = Requests()cookie := &http.Cookie{}cookie.Name   = "anewcookie"cookie.Value  = "20180825"cookie.Path   = "/"req.SetCookie(cookie)fmt.Println(req.Cookies)req.Get("https://www.httpbin.org/cookies/set?freeform=1234")req.Get("https://www.httpbin.org")req.Get("https://www.httpbin.org/cookies/set?a=33d")

!!! Process description
HTTP is used first in the code. A cookie generates a user-defined Cooie,
Req. Setcookie actually hasn't put cookies in Client.jar.
At get, requests will copy the contents of req.cookies into Client.jar and empty the Req.cookies
Once again get, requests will process cookies.

Debug

When debug = 1 is set, the request and the response are printed.

Contains the cookie for request and the returned cookie is not printed.

req := Requests()req.Debug = 1data := Datas{    "comments": "ew",    "custemail": "a@231.com",    "custname": "1",    "custtel": "2",    "delivery": "12:45",    "size": "small",    "topping": "bacon",  }resp,_ := req.Post("https://www.httpbin.org/post",data)fmt.Println(resp.Text())

The Debug results are as follows

===========go Requestdebug ============post/post http/1.1host:www.httpbin.orguser-agent:go-requests 0.5content-length:96content-type:application/x-www-form-urlencodedaccept-encoding:gzip===========go Responsedebug ============http/1.1 okcontent-length:560access-control-allow-credentials: Trueaccess-control-allow-origin: *connection:keep-alivecontent-type:application/jsondate:sun, Sep 2018 09:40:32 gmtserver:gunicorn/19.9.0via:1.1 vegur{"args": {}, "Data": "", "Files": {}, "form": {"comments": "EW", "Cust Email ":" a@231.com "," CustName ":" 1 "," Custtel ":" 2 "," Delivery ":" 12:45 "," Size ":" Small "," topping ":" BAC On "}," headers ": {" accept-encoding ":" gzip "," Connection ":" Close "," Content-length ":" $ "," Content-type "   : "application/x-www-form-urlencoded", "Host": "www.httpbin.org", "user-agent": "Go-requests 0.5"}, "JSON": null, "Origin": "219.143.154.50", "url": "Https://www.httpbin.org/post"}

Authentication verify the user name and password.

req = Requests()url1 := "https://www.httpwatch.com/httpgallery/authentication/authenticatedimage/default.aspx?0.45874470316137206"resp,_ = req.Get(url1,Auth{"httpwatch","foo"})fmt.Println(resp.httpresp)

The user name and password parameters are encrypted in the header,

And the params are different.

SaveFile

Then the above example, if successful. The returned data is actually a JPEG format file.

We can save the file directly.

resp.SaveFile("auth.jpeg")

Json

req = Requests()req.Header.Set("Content-Type","application/json")resp,_ = req.Get("https://httpbin.org/json")var json map[string]interface{}resp.Json(&json)for k,v := range json{  fmt.Println(k,v)}

Supports gzip format

req = Requests()req.Debug = 1resp,_ = req.Get("https://httpbin.org/gzip")fmt.Println(resp.Text())

Support for file post

req = Requests()req.Debug = 1path, _ := os.Getwd()path1 := path +  "/../examples/net1.go"path2 := path +  "/../examples/net2.go"resp,_ = req.Post("https://www.httpbin.org/post",data,Files{"a":path1,"b":path2})fmt.Println(resp.Text())

Header,params, is not divided into get and post.

Back to Cookies

In fact, requests's cookies have always existed client.jar inside,

So it needs to be read from Client.jar.

resp,_ = req.Get("https://www.httpbin.org")coo := resp.Cookies()// coo is [] *http.Cookiesprintln("********cookies*******")for _, c:= range coo{  fmt.Println(c.Name,c.Value)}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.