The example in this article describes how the go language creates a Web server using an HTTP package. Share to everyone for your reference, specific as follows:
There are roughly two ways to write an HTTP Web server in Golang:
1 NET with net package. Listen to monitor the port
2 Use Net/http Package
Here is a discussion of how to create a Web server using the Net/http package
The net/http request provides a concrete implementation of the HTTP client and server side
HTTP Client
The first to see is get,post,postform three functions. These three functions directly implement the HTTP client
Copy Code code as follows:
Import (
"FMT"
"Net/http"
"Io/ioutil"
)
Func Main () {
Response,_: = http. Get ("http://www.baidu.com")
Defer response. Body.close ()
Body,_: = Ioutil. ReadAll (response. Body)
Fmt. Println (String (body))
}
In addition to using these three functions to establish a simple client, you can also use:
http. Client and Http.newrequest to simulate requests
Copy Code code as follows:
Package Main
Import (
"Net/http"
"Io/ioutil"
"FMT"
)
Func Main () {
Client: = &http. client{}
Reqest, _: = http. Newrequest ("Get", "http://www.baidu.com", nil)
Reqest. Header.set ("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
Reqest. Header.set ("Accept-charset", "gbk,utf-8;q=0.7,*;q=0.3")
Reqest. Header.set ("accept-encoding", "GZIP,DEFLATE,SDCH")
Reqest.Header.Set ("Accept-language", "zh-cn,zh;q=0.8")
Reqest. Header.set ("Cache-control", "max-age=0")
Reqest. Header.set ("Connection", "keep-alive")
Response,_: = client. Do (reqest)
If response. StatusCode = 200 {
Body, _: = Ioutil. ReadAll (response. Body)
BODYSTR: = string (body);
Fmt. Println (BODYSTR)
}
}
How do I create a Web service side?
HTTP package is very BT, only need two lines!! :
Copy Code code as follows:
Package Main
Import (
"Net/http"
)
Func SayHello (w http. Responsewriter, req *http. Request) {
W.write ([]byte ("Hello"))
}
Func Main () {
http. Handlefunc ("/hello", SayHello)
http. Listenandserve (": 8001", nil)
}
Port monitoring: HTTP. Listenandserve (": 8001", nil)
Registration Path handler function: http. Handlefunc ("/hello", SayHello)
handler function: Func SayHello (w http. Responsewriter, req *http. Request)
What about the efficiency of the Golang server?
Look at this post:
Http://groups.google.com/group/golang-nuts/browse_thread/thread/cde2cc6278cefc90
Node.js is 45% faster than Golang (really sad)
The efficiency of the Golang service is indeed not node.js high, almost half of it. But then again, if some concurrent quantity is not very big site, still can use Golang do server.
I hope this article will help you with your go language program.