我正在制作一个 Go 网站(小型服务),但不知道如何 页面 URL 被验证为正确或未找到 404。最终我了解到存在 http 请求路由器/多路复用器。
例子:
eg.com/articles/animals/Hippos-are-aquatic-and-land-dwelling = go to page
eg.com/articles/animals/Hippos-are-typofrifjirj = 404 not found page
现在我只看到一种方法可以做到这一点,您可以通过某种方式获得网站上的文章列表,然后以某种方式将其传递到路由器中。您应该如何获得该文章列表?
对于动态关系数据库站点: 您是否在数据库中查询文章标题,并将其设为 map 字符串?
对于静态网站上的静态文件: 您在路由器或 net/http 中使用了一些 http 文件服务器目录功能?
如果是这样,对于数据库,是否意味着每次访问页面时都必须查询数据库?还是将文章列表存储在文件或其他内容中,并在每次制作新文章时更新它?
另外,我打算使用 https://github.com/julienschmidt/httprouter 或类似的。
最佳答案
假设路径中 /articles/animals/
之后的所有内容都是文章的 id,下面是使用 net/http 路由器的方法:
使用尾部斜杠注册处理程序以匹配所有带有前缀“/articles/animals/”的路径:
mux.HandleFunc("/articles/animals/", animalHandler)
在处理程序中,剥离 /articles/animals/
以获取文章的 id。在数据库中查找文章。如果不存在,则响应 404。
func animalHandler(w http.ResponseWriter, r *http.Request) {
id := strings.TrimPrefix(r.URL.Path, "/articles/animals/"))
article, err := queryArticleByID(id)
if err == errNotFound {
http.Error(w, "internal error", http.StatusNotFound)
return
} else if err != nil {
log.Println(err)
http.Error(w, "internal error", http.StatusInternalError)
}
... render the article
}
此示例假定 queryArticleByID()
函数查询数据库并返回 errNotFound
(如果没有文章对应给定的 ID)。
关于缓存:queryArticleByID()
可以在查询数据库之前检查缓存。任何缓存都与路由的处理方式无关。
关于http - 将 URL 路径与页面名称与 Go 中的 URL 路由匹配的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47148240/