如何使用相同的端口地址和不同的句柄模式同时提供网页和 API 路由 [英] How do I serve both web pages and API Routes by using same port address and different Handle pattern
问题描述
我有一个带有 CRUD 操作的简单 Web 应用程序,我想使用相同的端口地址和不同的句柄模式来提供网页和 API 路由.如下,
I have simple web application with CRUD operation, I want to serve web pages and API routes using same port address and different Handle pattern. As follows,
fs := http.FileServer(http.Dir("server/webapps/play_maths"))
http.Handle("/", fs)
http.Handle("/api", call API routes)
以下是我的 API 路由
Following is my API routes
func UserRoutes() *mux.Router {
var router = mux.NewRouter()
router = mux.NewRouter().StrictSlash(true)
router.HandleFunc("/user/create", api.CreateUser)
router.HandleFunc("/user/get/all", api.GetAllUsers)
return router
}
推荐答案
net/http
包开箱即用.引用自 http.ServeMux
:
模式命名固定的根路径,如/favicon.ico",或根子树,如/images/"(注意尾部斜杠).较长的模式优先于较短的模式,因此如果/images/"和/images/thumbnails/"都注册了处理程序,则将为以/images"开头的路径调用后一个处理程序/thumbnails/",前者将接收对/images/"子树中任何其他路径的请求.
Patterns name fixed, rooted paths, like "/favicon.ico", or rooted subtrees, like "/images/" (note the trailing slash). Longer patterns take precedence over shorter ones, so that if there are handlers registered for both "/images/" and "/images/thumbnails/", the latter handler will be called for paths beginning "/images/thumbnails/" and the former will receive requests for any other paths in the "/images/" subtree.
因此,您可以简单地将文件处理程序注册到路径 /
,并将 API 处理程序注册到例如/api/
路径.在这种情况下,任何以 /api/
开头的请求都将被定向到 API 处理程序,而任何其他请求将被定向到文件处理程序.
So simply you can register your file handler to path /
, and register an API handler to e.g. /api/
path. In this scenario any requests that start with /api/
will be directed to the API handler, and any other requests will be directed to the file handler.
请注意,这当然意味着如果 /api/
文件夹中存在文件(或者更具体地说,其请求路径以 /api/
开头),它们由于上述原因,将无法访问.
Note that this of course means if there are files that are in the /api/
folder (or more specifically whose request paths start with /api/
), they won't be reachable for the above mentioned reason.
这篇关于如何使用相同的端口地址和不同的句柄模式同时提供网页和 API 路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!