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

标签 api http go

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

相关文章:

用于获取内存和文件句柄计数的 C API

javascript - Trello API : list all cards for a given date range considering last activity date of the card in Trello?

http - 编写可以监听http请求的桌面客户端

ruby-on-rails - 如果我使用域名而不是 ip 地址,http 请求需要时间

json - 当 Go 的 JSON 包提到 Marshal 时是什么意思?

go - go-logr 和 uber 的 zap 详细级别之间的对应关系是什么?

c# - 如何在 EWS API 上下载特定文件附件

web-services - REST API - 单个资源的更新会更改多个其他资源

mongodb - 来自 MongoDB 的 alpha 驱动程序的简单 CRUD 示例

html - 使用 Wikipedia API 时,如何检索样式表?