search
HomeBackend DevelopmentGolangGo&#s http.ServeMux Is All You Need

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)
}

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

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)
})

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)
}

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

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)
})

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
Implementing Mutexes and Locks in Go for Thread SafetyImplementing Mutexes and Locks in Go for Thread SafetyMay 05, 2025 am 12:18 AM

In Go, using mutexes and locks is the key to ensuring thread safety. 1) Use sync.Mutex for mutually exclusive access, 2) Use sync.RWMutex for read and write operations, 3) Use atomic operations for performance optimization. Mastering these tools and their usage skills is essential to writing efficient and reliable concurrent programs.

Benchmarking and Profiling Concurrent Go CodeBenchmarking and Profiling Concurrent Go CodeMay 05, 2025 am 12:18 AM

How to optimize the performance of concurrent Go code? Use Go's built-in tools such as getest, gobench, and pprof for benchmarking and performance analysis. 1) Use the testing package to write benchmarks to evaluate the execution speed of concurrent functions. 2) Use the pprof tool to perform performance analysis and identify bottlenecks in the program. 3) Adjust the garbage collection settings to reduce its impact on performance. 4) Optimize channel operation and limit the number of goroutines to improve efficiency. Through continuous benchmarking and performance analysis, the performance of concurrent Go code can be effectively improved.

Error Handling in Concurrent Go Programs: Avoiding Common PitfallsError Handling in Concurrent Go Programs: Avoiding Common PitfallsMay 05, 2025 am 12:17 AM

The common pitfalls of error handling in concurrent Go programs include: 1. Ensure error propagation, 2. Processing timeout, 3. Aggregation errors, 4. Use context management, 5. Error wrapping, 6. Logging, 7. Testing. These strategies help to effectively handle errors in concurrent environments.

Implicit Interface Implementation in Go: The Power of Duck TypingImplicit Interface Implementation in Go: The Power of Duck TypingMay 05, 2025 am 12:14 AM

ImplicitinterfaceimplementationinGoembodiesducktypingbyallowingtypestosatisfyinterfaceswithoutexplicitdeclaration.1)Itpromotesflexibilityandmodularitybyfocusingonbehavior.2)Challengesincludeupdatingmethodsignaturesandtrackingimplementations.3)Toolsli

Go Error Handling: Best Practices and PatternsGo Error Handling: Best Practices and PatternsMay 04, 2025 am 12:19 AM

In Go programming, ways to effectively manage errors include: 1) using error values ​​instead of exceptions, 2) using error wrapping techniques, 3) defining custom error types, 4) reusing error values ​​for performance, 5) using panic and recovery with caution, 6) ensuring that error messages are clear and consistent, 7) recording error handling strategies, 8) treating errors as first-class citizens, 9) using error channels to handle asynchronous errors. These practices and patterns help write more robust, maintainable and efficient code.

How do you implement concurrency in Go?How do you implement concurrency in Go?May 04, 2025 am 12:13 AM

Implementing concurrency in Go can be achieved by using goroutines and channels. 1) Use goroutines to perform tasks in parallel, such as enjoying music and observing friends at the same time in the example. 2) Securely transfer data between goroutines through channels, such as producer and consumer models. 3) Avoid excessive use of goroutines and deadlocks, and design the system reasonably to optimize concurrent programs.

Building Concurrent Data Structures in GoBuilding Concurrent Data Structures in GoMay 04, 2025 am 12:09 AM

Gooffersmultipleapproachesforbuildingconcurrentdatastructures,includingmutexes,channels,andatomicoperations.1)Mutexesprovidesimplethreadsafetybutcancauseperformancebottlenecks.2)Channelsofferscalabilitybutmayblockiffullorempty.3)Atomicoperationsareef

Comparing Go's Error Handling to Other Programming LanguagesComparing Go's Error Handling to Other Programming LanguagesMay 04, 2025 am 12:09 AM

Go'serrorhandlingisexplicit,treatingerrorsasreturnedvaluesratherthanexceptions,unlikePythonandJava.1)Go'sapproachensureserrorawarenessbutcanleadtoverbosecode.2)PythonandJavauseexceptionsforcleanercodebutmaymisserrors.3)Go'smethodpromotesrobustnessand

See all articles

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

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)