This is a creation in Article, where the information may have evolved or changed.
The previous section has introduced the Web is a service based on the HTTP protocol, the Go language provides a complete net/http package, through the HTTP package can be very convenient to build up a running Web service. At the same time using this package can be very simple to the Web routing, static files, templates, cookies and other data set and operation.
HTTP Package Build Web server
PackageMainImport("FMT" "Net/http" "Strings" "Log") Func sayhelloname (w http. Responsewriter, R *http. Request) {r.parseform ()//parse parameter, default is not resolvedFmt.Println(R.form)//This information is output to the server-side printing informationFmt.Println("Path", 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("val:", strings.Join(V,"")} FMT. fprintf (W,"Hello astaxie!")//This write to W is output to the client's}func Main () {http. Handlefunc ("/", Sayhelloname)//Set access routesERR: = http. Listenandserve (": 9090", nil)//Set the listening port ifErr! = Nil {log. Fatal ("Listenandserve:", err)}}
Above this code, after we build, and then execute Web.exe, this time actually already on 9090 Port listening HTTP link request.
In the browser inputhttp://localhost:9090
You can see the browser page outputHello astaxie!
You can try a different address:http://localhost:9090/?url_long=111&url_long=222
See what the browser output is, what is the server output?
The information that is output on the server side is as follows:
Figure 3.8 Information on server-side printing after a user accesses the web
We see the code above, to write a Web server is very simple, just call the HTTP packet two functions can be.
If you were a PHP programmer before, you might ask, does our nginx, Apache server need it? Go just don't need this, because he listens to the TCP port directly, does the thing that Nginx does, then sayhelloname this is actually the logic function that we write, is similar with the control layer (Controller) function inside PHP.
If you were a Python programmer before, you must have heard of tornado, which is not like him, yes, go is a dynamic language like Python, writing Web applications is very convenient.
If you used to be a ruby programmer, you'll find that the Ror/script/server boot is a bit similar.
We see that go has a Web service running through a few simple lines of code, and this Web service has a feature that supports high concurrency, and I'll explain in more detail in the next two sections how go makes the Web high concurrency.