Golang HTTP Client

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Get, Head, Post, and Postform can make up HTTP (or HTTPS) requests:


RESP, err: = http. Get ("http://example.com/") ... resp, err:= http. Post ("Http://example.com/upload","Image/jpeg", &buf) ... resp, err:= http. Postform ("Http://example.com/form", URL. values{"Key": {"Value"},"ID": {"123"}})

The client must close the body of response:

RESP, err: = http. Get ("http://example.com/")if err! = Nil    {// Handle Error }defer resp. Body.close () body, err:= ioutil. ReadAll (resp. Body)//  ...

TCP Client Setting Timeout method:

 c:  = HTTP. client{Transport:  &http. transport{Dial:func (netw, addr  string  " (net). Conn, error) {deadline:  = time. Now (). ADD (25  * time. Second) C, err:  = net. Dialtimeout (NETW, addr, time. Second*20  )  if  err!= nil { return nil, err} c.setdeadline (deadline)  
  
   return  
    C, nil},},}  
  

Additional settings for some client requests:

Client: = &http. client{Checkredirect:redirectpolicyfunc,}resp, err:= client. Get ("http://example.com")// ...req, err:= http. Newrequest ("GET","http://example.com", nil)// ...Req. Header.add ("If-none-match", ' w/"Wyzzy"') RESP, err:=client. Do (req)// ...

If you want to bring the post data inside the Newrequest, you must pass in an IO. Reader body, this body if the IO is implemented. Closer, the returned Request.body is assigned to the body and is then closed via do or post or whatever. This implements the IO. The body of reader is basically the URL of a query that consists of a=1&b=2. Values can be converted by URL. Values.add and set build, the former can overlay, the latter will overwrite the previous value, Url.values has a encode can be converted to the corresponding query string, and then converted to IO by Strings.newreader (). Reader interface, it's all right. You can also pass ioutil. Nopcloser returns a io.reader with closer

In addition to the post data, remember to bring the top:

Req. Header.set ("content-type""application/x-www-form-urlencoded" )

I don't know what that means.

For control over proxies, TLS configuration, keep-alives, compression, and other settings, create a Transport:

TR: = &http. transport{    tlsclientconfig:    &TLS. Config{rootcas:pool},    true,}client:= &http. CLIENT{TRANSPORT:TR}RESP, err:= client. Get ("https://example.com")

A specific example:

Package Mainimport ("FMT"    "Io/ioutil"    "net/http"    "Net/url"    "Net"    " Time"    "OS"    "Strings")//func Nothing () {//FMT. Println ("Nothing")//client: = &http. client{}//A: = Strings. Contains ("A", "B")//U:=&url. url{}//r, Err: = U.parse ("baidu.com")//OS. Exit (0)// }Const(Lhst="http://127.0.0.1:3000/") Func main () {client:= &http. client{Transport:&http. transport{Dial:func (netw, addrstring) (NET. Conn, error) {deadline:= time. Now (). ADD ( -*Time . Second) C, err:= Net. Dialtimeout (NETW, addr, time. second* -)                ifErr! =Nil {returnnil, err} c.setdeadline (deadline)returnC, nil},},} form:=URL. values{} form. Set ("username","Gao") B:=strings. Newreader (form. Encode ()) req, err:= http. Newrequest ("POST", lhst+"Answer", B) req. Header.set ("Content-type","application/x-www-form-urlencoded") Res, err:=client. Do (req)ifErr! =Nil {fmt. Println ("Fatal Error", Err. Error ()) OS. Exit (0)} defer res. Body.close () Body,err:=Ioutil. ReadAll (Res. Body) fmt. Println (string(body))}
Let me give you an example.

Func Main () {host:="http://www.minigps.net/l.do?"Client:=http. client{} Q:=URL. values{} q.set ("C","454") Q.set ("N","6") Q.set ("a","8010") Q.set ("e","6652663") Req, _:= http. Newrequest ("GET", host+Q.encode (), nil) req. Header.add ("Content-type","Application/json;charset=utf-8") Res, err:=client. Do (req)ifErr! =Nil {fmt. PRINTLN (ERR) OS. Exit (-1)} defer res. Body.close () body, err:=Ioutil. ReadAll (Res. Body) fmt. Println (string(body))}

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.