This is a creation in Article, where the information may have evolved or changed.
Original link: http://blog.csdn.net/cc7756789w/article/details/51014076
Author: pastoral
Github:https://github.com/zhanghang-z
Reprint please indicate the source, not for commercial purposes without the author's permission.
Use the Net/http package to quickly create an HTTP server.
//File Http_test1.go PackageMainImport("FMT" "Net/http" "Log")funcHandleindex (w http. Responsewriter, R *http. Request) {r.parseform () fmt. Println ("PATH:", R.url. Path) fmt. Println (" SCHEME:", R.url. Scheme) fmt. Println ("METHOD:", R.method) fmt. Println () fmt. fprintf (W,")}funcMain () {http. Handlefunc ("/", handleindex) Err: = http. Listenandserve (": 8000",Nil)ifErr! =Nil{log. Fatal ("ERROR:", err)}}
In fact, sometimes language does not matter, the principle is probably the same. This handler
is like the Python Wsgi protocol application(environ, start_response)
, like the Nodejs callback(req,res)
function. And they're all based on sockets (like YES!!!) )
$ go run http_test1.go
Enter in the browser 127.0.0.1:8000
to see the browser display:
Print out the following information on the terminal:
Although we do not listen to the port as explicitly as other languages, start the server, or use a socket to build a TCP or UDP server, use a while loop to get the request data. But it is not difficult to find the entrance of the service in http.ListenAndServe
. Let's take a look at the source code and discuss what it does.
$ godoc -src net/http ListenAndServe
Will print out two similar functions:
func (srv *Server) ListenAndServe() error { addr := srv.Addr if"" { ":http" } ln, err := net.Listen("tcp", addr) ifnil { return err } return srv.Serve(tcpKeepAliveListener{ln.(*net.TCPListener)})}funcstring, handler Handler) error { server := &Server{Addr: addr, Handler: handler} return server.ListenAndServe()}
Do not think that the two functions of the same name are overloaded functions like C + + or Java, and that there is no concept of function signing in the Go language.
The first function func (srv *Server) ListenAndServe() error
, which is type Server struct
the type of a method that you can understand as an object-oriented method, belongs to the server class.
The second function func ListenAndServe(addr string, handler Handler) error
is a normal function, which is encapsulated internally and implements the HTTP server more succinctly. You can see that it creates an object of the server class and then calls the first function that was just said.