Table of Contents
Optimization and application analysis of http.ServeMux in Go 1.22 standard library
1. Highlights of Go 1.22: Enhanced pattern matching capabilities
2. How to use the new mux
(1) Basic usage examples
(2) Mode conflict handling
3. Use the new MUX to implement the server
(1) Mode registration example
(2) The process of processing program
Leapcell: The most suitable for GO application hosting, asynchronous task, and the server -free platform of Redis
Home Backend Development Golang Go&#s http.ServeMux Is All You Need

Go&#s http.ServeMux Is All You Need

Jan 27, 2025 pm 10:07 PM

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:

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)
}
Copy after login
Copy after login

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:

$ 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
Copy after login
Copy after login

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:

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)
})
Copy after login
Copy after login

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:

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)
}
Copy after login
Copy after login

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:

$ 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
Copy after login
Copy after login

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:

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)
})
Copy after login
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1252
29
C# Tutorial
1226
24
Golang's Purpose: Building Efficient and Scalable Systems Golang's Purpose: Building Efficient and Scalable Systems Apr 09, 2025 pm 05:17 PM

Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

Golang and C  : Concurrency vs. Raw Speed Golang and C : Concurrency vs. Raw Speed Apr 21, 2025 am 12:16 AM

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Golang vs. Python: Key Differences and Similarities Golang vs. Python: Key Differences and Similarities Apr 17, 2025 am 12:15 AM

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

The Performance Race: Golang vs. C The Performance Race: Golang vs. C Apr 16, 2025 am 12:07 AM

Golang and C each have their own advantages in performance competitions: 1) Golang is suitable for high concurrency and rapid development, and 2) C provides higher performance and fine-grained control. The selection should be based on project requirements and team technology stack.

Golang's Impact: Speed, Efficiency, and Simplicity Golang's Impact: Speed, Efficiency, and Simplicity Apr 14, 2025 am 12:11 AM

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:

C   and Golang: When Performance is Crucial C and Golang: When Performance is Crucial Apr 13, 2025 am 12:11 AM

C is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.

Golang and C  : The Trade-offs in Performance Golang and C : The Trade-offs in Performance Apr 17, 2025 am 12:18 AM

The performance differences between Golang and C are mainly reflected in memory management, compilation optimization and runtime efficiency. 1) Golang's garbage collection mechanism is convenient but may affect performance, 2) C's manual memory management and compiler optimization are more efficient in recursive computing.

See all articles