Home > Article > Backend Development > How to Serve Web Pages and API Routes on the Same Port with Different Handle Patterns in Go?
Serving Web Pages and API Routes on the Same Port with Different Handle Patterns
In a web application where both web pages and API routes need to be served on the same port, it's possible to achieve this using the net/http package provided by the Go standard library. The key principle is the precedence of longer patterns over shorter ones.
Consider the following code snippet:
fs := http.FileServer(http.Dir("server/webapps/play_maths")) http.Handle("/", fs) // Serves static web pages from the specified directory http.Handle("/api", api.UserRoutes()) // Handles API routes using the UserRoutes function
In this example, the file handler is registered for the root URL path "/", which means it will handle any requests that don't match a longer pattern. The API routes handler is then registered for the "/api" path. Since "/api" is a longer pattern than "/", any request that starts with "/api" will be directed to the API routes handler, while all other requests will go to the file handler.
Note that it's important to ensure that no files exist within the "/api" directory, as they would be inaccessible due to the precedence rule. By leveraging the pattern precedence feature, it's possible to serve web pages and API routes on the same port using different handlers.
The above is the detailed content of How to Serve Web Pages and API Routes on the Same Port with Different Handle Patterns in Go?. For more information, please follow other related articles on the PHP Chinese website!