Home >Backend Development >Golang >Go&#s http.ServeMux Is All You Need

Go&#s http.ServeMux Is All You Need

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-27 22:07:10976browse

Optimization and application analysis of http.ServeMux in Go 1.22 standard library

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.

1. Highlights of Go 1.22: Enhanced pattern matching capabilities

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.

2. How to use the new 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.

(1) Basic usage examples

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:

  1. In the first handler, the HTTP method (GET in this case) is explicitly used as part of the pattern. This means that this handler only responds to GET requests for paths starting with /path/ and will not handle requests for other HTTP methods.
  2. In the second handler, the second path component {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 {$}.

(2) Mode conflict handling

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.

3. Use the new MUX to implement the server

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.

(1) Mode registration example

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.

(2) The process of processing program

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.

Four, conclusion

"Which route should I choose?" It has always been a common problem facing GO beginners. After GO 1.22 is released, the answer to this question may change. Many developers will find that the new standard library MUX is enough to meet their needs, so that they need to rely on third -party packages.

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.

Go

Leapcell: The most suitable for GO application hosting, asynchronous task, and the server -free platform of Redis

Finally, recommend a platform that is most suitable for deploying Go services: Leapcell

  1. Multi -language support
    Use JavaScript, Python, GO or Rust for development.
    Free deployment unlimited project
    Just pay for use -no request, no cost.
    Unparalleled cost benefits
    Pay on demand, no idle costs.
  • Example: $ 25 supports 6.94 million requests, with an average response time of 60 milliseconds.
    Simplified developer experience
    intuitive UI, easy settings.
  • Completely automated CI/CD pipeline and GitOps integration.
  • Real -time indicators and log records provide operating insights.
    Easy expansion and high performance
    Automatic extension to easily handle high and merger.
  • Zero operation expenses -just focus on construction.
Leapcell Twitter:

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 Go&#s http.ServeMux Is All You Need. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn