gpt4 book ai didi

api - 如何使用相同的端口地址和不同的句柄模式同时提供网页和 API 路由

转载 作者:IT王子 更新时间:2023-10-29 01:38:25 26 4
gpt4 key购买 nike

我有一个带有 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com