Home > Article > Backend Development > How to Serve Web Pages and API Routes on the Same Port with Different Handle Patterns?
In a web application scenario, it can be convenient to serve both static web pages and API routes on the same port address. This allows for a streamlined architecture and efficient resource utilization. To achieve this using different handle patterns, follow these steps:
1. Register File Handler
Register a file server to serve static files. In this example, it is used to serve files from the "server/webapps/play_maths" directory at the root path (/):
fs := http.FileServer(http.Dir("server/webapps/play_maths")) http.Handle("/", fs)
2. Register API Handler
Create a router for handling API routes. In this case, UserRoutes() defines routes for creating users and retrieving all users:
func UserRoutes() *mux.Router { router := mux.NewRouter().StrictSlash(true) router.HandleFunc("/user/create", api.CreateUser) router.HandleFunc("/user/get/all", api.GetAllUsers) return router }
3. Attach API Handler to Path
Register the API router to a specific root path, such as "/api/". This ensures that all requests starting with "/api/" will be handled by the API routes:
http.Handle("/api/", UserRoutes())
Note: The order of route registration matters. Longer patterns take precedence over shorter ones. Therefore, it is important to register the more specific API routes before the general file handler. This prevents requests to the API routes from being intercepted by the file handler.
By following these steps, you can serve both static web pages and API routes on the same port address while maintaining different handle patterns. This provides flexibility and improves performance by reducing the need for multiple server instances.
The above is the detailed content of How to Serve Web Pages and API Routes on the Same Port with Different Handle Patterns?. For more information, please follow other related articles on the PHP Chinese website!