Golang Net/http Package Use

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

HTTP Client

Import "Net/http"
The HTTP package provides the HTTP client and server implementations.

The, post, and Postform functions make HTTP/HTTPS requests.

package mainimport (    "fmt"    "io/ioutil"    "net/http")func main() {    response, err := http.Get("http://www.baidu.com")    ifnil {    // handle error    }    //程序在使用完回复后必须关闭回复的主体。    defer response.Body.Close()    body, _ := ioutil.ReadAll(response.Body)    fmt.Println(string(body))}
 PackageMainImport("FMT"    "Io/ioutil"    "Net/http"    "bytes")funcMain () {body: ="{\" action\ ": "Res, ERR: = http. Post ("Http://xxx.com","Application/json;charset=utf-8", bytes. Newbuffer ([]byte(body)))ifErr! =Nil{FMT. Println ("Fatal Error"Err. Error ())}deferRes. Body.close () content, err: = Ioutil. ReadAll (Res. Body)ifErr! =Nil{FMT. Println ("Fatal Error"Err. Error ())} FMT. Println (string(content))}

You can also use:
http. Client and Http.newrequest to simulate the request

 PackageMainImport("FMT"    "Io/ioutil"    "Net/http"    "Net/url"    "Strings")funcMain () {V: = URL. values{} v.set ("username","xxxx") V.set ("Password","xxxx")returns a new request with the specified Method,url and optional body. If the body parameter implements the Io.closer interface, the body field of the request return value is set to body and will be the client type of do, The Post and Postform methods and the Transport.roundtrip method are closed. Body: = Ioutil. Nopcloser (Strings. Newreader (V.encode ()))//Coding the form dataClient: = &http. client{}//client, used by Get,head and postReqest, Err: = http. Newrequest ("POST","Http://xxx.com/logindo", body)ifErr! =Nil{FMT. Println ("Fatal Error"Err. Error ())}//Set the value of the response to a key.Reqest. Header.set ("Content-type","Application/x-www-form-urlencoded;param=value")//must set this parameter for post parameters to be submitted normallyRESP, err: = client. Do (reqest)//Send request    deferResp. Body.close ()//Be sure to turn off resp. BodyContent, Err: = Ioutil. ReadAll (resp. Body)ifErr! =Nil{FMT. Println ("Fatal Error"Err. Error ())} FMT. Println (string(content))}

How do I create a Web service side?

package mainimport (    "net/http")func SayHello(w http.ResponseWriter, req *http.Request) {    w.Write([]byte("Hello"))}func main() {    http.HandleFunc("/hello", SayHello)    http.ListenAndServe(":8001"nil)}

First Call Http.handlefunc
In order to do a few things:
* Call the Handlefunc of Defaultservermux
* Call the handle of Defaultservermux
* Add corresponding handler and routing rules to the map[string]muxentry in Defaultservemux

Next, call HTTP. Listenandserve (": 8001", nil)
In order to do a few things:
* Instantiate server
* Call server's Listenandserve ()
* Call NET. Listen ("tcp", addr) Listening port
* Start A For loop, accept requests in the loop body
* Instantiate a conn for each request and open a Goroutine to service the request Go C.serve ()
* Read the contents of each request W, err: = C.readrequest ()
* Determine if the header is empty, if not set handler (this example does not set handler), handler is set to Defaultservemux
* Call Handler's servehttp
* In this example, the following goes into the Defaultservermux.servehttp
* Select handler according to request and enter into this handler servehttp

   mux.handler(r).ServeHTTP(w, r)

* Select handler:

A 判断是否有路由能满足这个request(循环遍历ServerMux的muxEntry)B 如果有路由满足,调用这个路由handler的ServeHttpC 如果没有路由满足,调用NotFoundHandler的ServeHttp

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

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.