Golang implementation of a simple HTTP route and its principle

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.
    1. Premise: To implement an HTTP route must understand the Net/http package, mainly the Go/src/net/http/server.go file
    2. Go implements a web route to do three main things:
      • Listening port
      • Receiving requests from clients
      • Assign a corresponding handler to each request (in PHP it is to forward the request to the appropriate controller and action)

The following is a simple logic to implement routing

package mainimport (        "fmt"        "net/http")func rootGateWay(w http.ResponseWriter, r *http.Request) {        println("Welcome to Chris's homepage! ")}func defaultGateWay(w http.ResponseWriter, r *http.Request) {        fmt.Fprintf(w, "Hello jingjing")        println("Welcome to Chris's homepage! ")}func main() {        http.HandleFunc("/", defaultGateWay)            http.ListenAndServe(":8080", nil)}//访问http://host:8080/ 即可看到Hello jingjin

From the above example, we performed a simple web route with only two steps and executed the Handlefunc and listenandserve two functions respectively. What do you do with each of these two functions?

First look at the following source code:

//调用默认ServerMux的HandleFunc方法func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {                                                                                                                         DefaultServeMux.HandleFunc(pattern, handler)}//把方法handler转换成HandlerFunc类型,即实现了Handler接口;再执行Handle方法func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {        mux.Handle(pattern, HandlerFunc(handler))}//路由器注册一个handler给指定的partternfunc (mux *ServeMux) Handle(pattern string, handler Handler) {        ....}

It is not difficult to see that the execution of Handlefunc is actually a request for a rule to register the processor.

Below we see what listenandserve have done, see the following section of the source code:

 func listenandserve (addr string, handler handler) error {//Initialize a server Struct assignment SE RVer address and handler, but handler is often empty because it will make//with Defaultservemux server: = &server{addr:addr, H                                                                                                                                                Andler:handler} return server. Listenandserve ()}//listens through the TCP network addr address func (SRV *server) listenandserve () error {addr: = srv.                                                                                                                                                                                        Addr if Addr = = "" { Addr = ": http"} LN , Err: = Net. Listen ("tcp", addr) if err! = Nil {return err}//for the Dead loop always accepts HTTP request, each request opens a new G Oroutine handles return SRV. Serve (Tcpkeepalivelistener{ln. ( *net. TcpListener)})}  

As a result, we can simply summarize what the above code does:

    • To register a route handler for a different URL rule
    • Create server and listen for ports
    • The For loop receives the request and processes it concurrently

PS: This issue is still relatively simple, the next phase to achieve a truly meet the business needs of the HTTP Routing and Web

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.