我有一个带有 CRUD 操作的简单 Web 应用程序,我想使用相同的端口地址和不同的句柄模式来提供网页和 API 路由。如下,
fs := http.FileServer(http.Dir("server/webapps/play_maths"))
http.Handle("/", fs)
http.Handle("/api", call API routes)
以下是我的 API 路线
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
:
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 处理程序,任何其他请求将定向到文件处理程序。
请注意,这当然意味着如果 /api/
文件夹中存在文件(或更具体地说,其请求路径以 /api/
开头),则它们由于上述原因将无法访问。
关于api - 如何使用相同的端口地址和不同的句柄模式来服务网页和 API 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47493820/