Serving Web Pages and API Routes on the Same Port with Different Handle Patterns
Serving both web pages and API routes on the same port using distinct handle patterns is a common requirement in web development. Here's how to achieve this in Go using the net/http package:
The net/http package provides the ServeMux type, which manages a set of handlers for incoming HTTP requests. Registration of handlers is done via the Handle method. As per the documentation, longer patterns take precedence over shorter ones. This property can be leveraged to serve web pages and API routes concurrently on the same port.
For example, to serve web pages under the root path / and API routes under /api, you can use the following code:
fs := http.FileServer(http.Dir("server/webapps/play_maths")) http.Handle("/", fs) // Handles web pages at root path apiRoutes := UserRoutes() // Initialize API routes as a handler http.Handle("/api", apiRoutes.ServeHTTP) // Handles API routes
The UserRoutes function creates a sub-router for API routes. By default, sub-routers inherit the parent router's prefix, but you can override this behavior using the PathPrefix method. The router is then used as a handler for our API routes.
By registering the web page handler before the API routes handler, ensuring that the web page handler has a shorter pattern, we are exploiting the fact that longer patterns take precedence. As a result, requests that start with /api will be handled by the API routes handler, while all other requests (including those to the root path) will be handled by the web page handler.
This approach provides a flexible way to handle different types of HTTP requests on the same server without the need to run multiple processes or use a reverse proxy.
The above is the detailed content of How to Serve Web Pages and API Routes on the Same Port in Go?. For more information, please follow other related articles on the PHP Chinese website!