Home > Article > Backend Development > How to Serve Web Pages and API Routes on the Same Port with Varied Handle Patterns?
Serving Web Pages and API Routes on the Same Port with Varied Handle Patterns
Developers often seek solutions to host web pages and API routes together with designated port addresses and handle patterns. To accomplish this, consider leveraging the capabilities offered by the net/http package.
As illustrated in the example code provided, you can employ the http.FileServer() function to establish a file server at the root URL ("/"). This ensures that static files stored in the specified directory can be accessed through this handle pattern.
To handle API routes, register a dedicated handler targeting the desired path, like "/api" in the example. Inside this handler, you can configure specific route patterns and their corresponding functions using a routing library like mux.Router .
For instance, the given API route demonstrates how to handle requests for user operations.
This approach is supported natively by the net/http package's intelligent pattern matching mechanism. Long-pattern routes take precedence over shorter ones. Thus, the API handler registered for "/api/" would intercept requests starting with "/api/", while the file handler would serve requests for any other paths under the "/api/" subtree.
The above is the detailed content of How to Serve Web Pages and API Routes on the Same Port with Varied Handle Patterns?. For more information, please follow other related articles on the PHP Chinese website!