Home >Backend Development >Golang >Gos http.ServeMux Is All You Need
In the field of Go Web development, in order to achieve more efficient and flexible routing functions, many developers choose to introduce third-party libraries such as httprouter and gorilla/mux. However, in Go 1.22 version, the official has significantly optimized http.ServeMux in the standard library, which is expected to reduce developers' dependence on third-party routing libraries.
Go 1.22 implements the highly anticipated proposal to enhance the pattern matching capabilities of the default HTTP service multiplexer in the standard library net/http package. The existing multiplexer (http.ServeMux) can only provide basic path matching functions, which is relatively limited, resulting in a large number of third-party libraries emerging to meet developers' needs for more powerful routing functions. The new multiplexers in Go 1.22 will significantly close the feature gap with third-party libraries by introducing advanced matching capabilities. This article will briefly introduce the new multiplexer (mux), provide an example REST server, and compare the performance of the new standard library mux with gorilla/mux.
For Go developers who have experience using third-party mux/routers (such as gorilla/mux), using the new standard mux will be a simple and familiar thing. It is recommended that developers first read its official documentation, which is concise and clear.
The following code demonstrates some of mux’s new pattern matching capabilities:
<code class="language-go">package main import ( "fmt" "net/http" ) func main() { mux := http.NewServeMux() mux.HandleFunc("GET /path/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "got path\n") }) mux.HandleFunc("/task/{id}/", func(w http.ResponseWriter, r *http.Request) { id := r.PathValue("id") fmt.Fprintf(w, "handling task with %s\n", id) }) http.ListenAndServe(":8090", mux) }</code>
Experienced Go programmers will immediately notice two new features:
/path/
and will not handle requests for other HTTP methods. {id}
contains wildcard characters, which was not supported in previous versions. This wildcard can match a single path component, and the handler can obtain the matching value via the request's PathValue
method. Here is an example of testing this server using the curl command:
<code class="language-bash">$ gotip run sample.go # 在另一个终端测试 $ curl localhost:8090/what/ 404 page not found $ curl localhost:8090/path/ got path $ curl -X POST localhost:8090/path/ Method Not Allowed $ curl localhost:8090/task/leapcell/ handling task with leapcell</code>
As can be seen from the test results, the server will reject POST requests for /path/
and only allow GET requests (curl uses GET requests by default). At the same time, when the request matches, the id
wildcard character will be assigned the corresponding value. Developers are advised to refer to the documentation of the new ServeMux in detail to learn more about features such as trailing path and {id}
wildcard matching rules, as well as strict matching of paths ending with {$}
.
This proposal pays special attention to possible conflicts between different modes. Here's an example:
<code class="language-go">mux := http.NewServeMux() mux.HandleFunc("/task/{id}/status/", func(w http.ResponseWriter, r *http.Request) { id := r.PathValue("id") fmt.Fprintf(w, "handling task status with %s\n", id) }) mux.HandleFunc("/task/0/{action}/", func(w http.ResponseWriter, r *http.Request) { action := r.PathValue("action") fmt.Fprintf(w, "handling task action with %s\n", action) })</code>
When the server receives a request for /task/0/status/
, both handlers can match this request. The new ServeMux documentation details mode precedence rules and how to handle potential conflicts. If a conflict occurs, the registration process will trigger a panic. For the example above, the following error message will appear:
<code class="language-go">package main import ( "fmt" "net/http" ) func main() { mux := http.NewServeMux() mux.HandleFunc("GET /path/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "got path\n") }) mux.HandleFunc("/task/{id}/", func(w http.ResponseWriter, r *http.Request) { id := r.PathValue("id") fmt.Fprintf(w, "handling task with %s\n", id) }) http.ListenAndServe(":8090", mux) }</code>
This error message is detailed and practical. In complex registration scenarios (especially when registering in multiple positions of the source code), these details can help developers quickly locate and solve conflict problems.
The REST server series in GO uses a variety of methods to implement a simple server in the task/to be applied in Go. The first part is based on the standard library, and the second part uses the Gorilla/MUX router to re -implement the same server. Now, using the GO 1.22 enhanced MUX to implement this server again is of great significance, and it is also interesting to compare it with solutions using Gorilla/MUX.
The following is part of the representative mode registration code:
<code class="language-bash">$ gotip run sample.go # 在另一个终端测试 $ curl localhost:8090/what/ 404 page not found $ curl localhost:8090/path/ got path $ curl -X POST localhost:8090/path/ Method Not Allowed $ curl localhost:8090/task/leapcell/ handling task with leapcell</code>
Similar to the Gorilla/MUX examples, here is a request routing to different processing procedures with the same path with a specific HTTP method. When using the old http.serVemux, this kind of matching device will directed the request to the same processing program, and then the processing program will determine the follow -up operation according to the request method.
The following is an example of a processing program:
<code class="language-go">mux := http.NewServeMux() mux.HandleFunc("/task/{id}/status/", func(w http.ResponseWriter, r *http.Request) { id := r.PathValue("id") fmt.Fprintf(w, "handling task status with %s\n", id) }) mux.HandleFunc("/task/0/{action}/", func(w http.ResponseWriter, r *http.Request) { action := r.PathValue("action") fmt.Fprintf(w, "handling task action with %s\n", action) })</code>
Here the process is extracted from req.PathValue("id")
to extract the ID value, which is similar to the Gorilla method. However, because the {id}
only matches the integer with a regular expression, it is necessary to pay attention to the error of strconv.Atoi
returned.
In general, the final result is very similar to a solution using Gorilla/MUX. Compared with the traditional standard library method, the new MUX can perform more complicated routing operations, reducing the needs of leaving the routing decision to the processing program itself, and improving development efficiency and code maintenance.
Of course, some developers will continue to choose familiar third -party libraries, which is also reasonable. Routers like Gorilla/MUX still have more functions than standard libraries. In addition, many Go programmers choose lightweight frameworks such as GIN because it not only provides routers, but also provides bidding tools needed to build a web back end.
In short, the optimization of the GO 1.22 standard library http.serv "optimization is undoubtedly a positive change. Regardless of whether developers choose to use a third -party package or insist on using the standard library, the function of enhancing the standard library is beneficial to the entire GO development community.
Finally, recommend a platform that is most suitable for deploying Go services: Leapcell
https://www.php.cn/link/7884effb9452a6d7a79499EF854AFD
(Note: Because I cannot access the picture link, I retain the picture label, please make sure the picture path is correct.)The above is the detailed content of Gos http.ServeMux Is All You Need. For more information, please follow other related articles on the PHP Chinese website!