This is a creation in Article, where the information may have evolved or changed.
There are roughly two ways to write an HTTP Web server in Golang:
1 NET package is used. Listen to listen to the port
2 Using the Net/http package
HTTP Client
Here is a discussion of how to create a Web server using the Net/http package
Net/http request provides a specific implementation of the HTTP client and server
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 build a simple client, you can also use:
http. Client and Http.newrequest to simulate the request
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 = = $ {body, _: = Ioutil. ReadAll (response. Body) Bodystr: = string (body); Fmt. Println (BODYSTR) }}
How do I create a Web service side?
HTTP packets are packaged in a very bt, only two lines required!! :
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)}
Listen for Port: http. Listenandserve (": 8001", nil)
Register the path handler function: http. Handlefunc ("/hello", SayHello)
handler function: Func SayHello (w http. Responsewriter, req *http. Request)