Package Mainimport ("net/http" "FMT" "Strings" "Log") Func sayhelloname (w http. Responsewriter, R*http. Request) {r.parseform () fmt. Println (R.form) fmt. Println ("URL", R.url. Path) fmt. Println ("Scheme", R.url. Scheme) fmt. Println (r.form["Url_long"]) forK, v:=range R.form {fmt. Println ("Key:", K) fmt. Println ("Value:", strings. Join (V,"") } fmt. Fprintln (W,"Hello Web")}func Main () {http. Handlefunc ("/", Sayhelloname) Err:= http. Listenandserve (": 9876", nil)iferr!=Nil {log. Fatal ("Listenandserve", Err)}}
Let's look at one of the most basic Golang Web server code. In main, the route is set in Handlefunc and then called Listenandserve to select the listening interface and routing method (where the routing method is empty, that is, the default route is called, that is, the route Handlefunc set).
Lestenandserve called the Serve method in the HTTP library, as follows:
Func (SRV *Server) Serve (l net. Listener) Error {defer l.close ()iffn: = Testhookserverserve; fn! =Nil {fn (SRV, l)}varTempdelay time. Duration//How long-to- sleep on accept failure ifERR: = Srv.setuphttp2_serve (); Err! =Nil {returnerr} srv.tracklistener (L,true) Defer Srv.tracklistener (L,false) Basectx:= Context. Background ()//base is always background, per Issue 16220CTX: =context. Withvalue (Basectx, Servercontextkey, SRV) for{rw, E:=l.accept ()ifE! =Nil {Select { Case<-Srv.getdonechan ():returnerrservercloseddefault: } ifNE, OK: = E. (NET. ERROR); OK &&NE. Temporary () {ifTempdelay = =0{Tempdelay=5*Time.millisecond}Else{Tempdelay*=2 } ifMax: =1* Time. Second; Tempdelay >Max {Tempdelay=Max} srv.logf ("http:accept Error:%v; retrying in%v", E, Tempdelay) time. Sleep (Tempdelay)Continue } returne} tempdelay=0C:=srv.newconn (rw) c.setstate (C.RWC, statenew)//before Serve can returngo C.serve (CTX)}}
As you can see, serve establishes a loop to listen for requests. After the connection request is received, the request is accepted, a new connection is made, and a new thread is created with go to process the connection. This is the root of Golang's support for high concurrency in processing Web requests. It also guarantees the independence of each connection.
Golang built-in library learning notes (2)-web Server related