Home >Backend Development >Golang >How to Serve Web Pages and API Routes on the Same Port with Different Patterns?

How to Serve Web Pages and API Routes on the Same Port with Different Patterns?

Susan Sarandon
Susan SarandonOriginal
2024-11-15 19:53:03748browse

How to Serve Web Pages and API Routes on the Same Port with Different Patterns?

Serving Web Pages and API Routes on Same Port with Different Patterns

In web applications, it's often desired to serve both static web pages and API routes using the same port address. To achieve this, you can leverage the pattern matching capabilities provided by the net/http package.

Registering a file handler for the root URL ("/") will serve static content from a specified directory. For example:

fs := http.FileServer(http.Dir("server/webapps/play_maths"))
http.Handle("/", fs)

To serve API routes, you can create a separate handler using a router like mux.Router. For example:

func UserRoutes() *mux.Router {
    router := mux.NewRouter().StrictSlash(true)
    router.HandleFunc("/user/create", api.CreateUser)
    router.HandleFunc("/user/get/all", api.GetAllUsers)
    return router
}

Registering this API router with a specific pattern allows you to handle API requests with different paths. For example:

http.Handle("/api", UserRoutes())

According to the net/http documentation, longer patterns take precedence over shorter ones. This means that any request starting with "/api/" will be handled by the API router, while any other request will be directed to the file handler.

Note that this approach requires careful consideration to prevent potential conflicts. For instance, if static files were placed within the "/api/" directory, they would no longer be accessible due to the API pattern taking precedence.

The above is the detailed content of How to Serve Web Pages and API Routes on the Same Port with Different Patterns?. 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