您的当前位置:首页http.ListenAndServe()到底做了什么?

http.ListenAndServe()到底做了什么?

来源:小侦探旅游网

实现一个最简短的hello world服务器


package main

import "net/http"

func main() {
   
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
   
		w.Write([]byte(`hello world`))
	})

	http.ListenAndServe(":3000", nil)
}
http.ListenAndServe()到底做了什么?

http.ListenAndServe()用到的所有依赖都在Go源码中的/src/pkg/net/http/server.go文件中,我们可以看到它的定义:

// ListenAndServe listens on the TCP network address srv.Addr and then
// calls Serve to handle requests on incoming connections.
// Accepted connections are configured to enable TCP keep-alives.
//
// If srv.Addr is blank, ":http" is used.
//
// ListenAndServe always returns a non-nil error. After Shutdown or Close,
// the returned error is ErrServerClosed.
func (srv *Server) ListenAndServe() error {
   
	if srv.shuttingDown() {
   
		return ErrServerClosed
	}
	addr := srv.Addr
  // 如果不指定服务器地址信息,默认以":http"作为地址信息
	if addr == "" {
   
		addr = ":http"
	}
  // 创建一个TCP Listener, 用于接收客户端的连接请求
	ln, err := net.Listen("tcp", addr)
	if err != nil {
   
		return err
	}
	return srv.Serve(ln)
}

最后调用了Server.Serve()并返回,继续来看Server.Serve():

// Serve accepts incoming connections on the Listener l, creating a
// new service goroutine for each. The service goroutines read requests and
// then call srv.Handler to reply to them.
//
// HTTP/2 support is only enabled if the Listener returns *tls.Conn
// connections and they were configured with "h2" in the TLS
// Config.NextProtos.
//
// Serve always returns a non-nil error and closes l.
// After Shutdown or Close, the returned error is ErrServerClosed.
func (srv *Server) Serve(l net.Listener) error {
   
	if fn := testHookServerServe; fn != nil {
   
		fn(srv, l) // call hook with unwrapped listener
	}

	origListener := l
	l = &onceCloseListener{
   Listener: l}
	defer l.Close()

	if err := srv.setupHTTP2_Serve(); err 

因篇幅问题不能全部显示,请点此查看更多更全内容