英文:
Map variable amount of urls to HandleFunc
问题
这是我第一次尝试使用Go(Golang)编写一个小型博客。现在,我有一个只有几个页面的小型网站。我的main
函数包含以下内容:
http.HandleFunc("/about", about)
http.HandleFunc("/contact", contact)
http.HandleFunc("/", homepage)
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatalln(err)
}
我的第一个问题是:这被称为什么?我称之为将URL映射到函数,但是我的谷歌搜索结果并不理想。这被称为"路由"吗?
其次,我的目标是编写一个小型博客应用程序。我想使用数据库来保存博客文章和其他数据。然而,像我上面那样将URL映射到函数似乎不太合适,因为在有人发布博客文章之前,无法知道URL应该是什么。我希望URL与博客文章的标题匹配。此外,可能会有数百篇博客文章,因此编写大量的http.HandleFunc
函数似乎不合理。
最后,我的问题是:有哪些选项可用来解决这个障碍?
英文:
This is the first time that I attempt to write a small blog using Go (Golang). Right now, I have a small website running with only a few pages. My main
contains this.
http.HandleFunc("/about", about)
http.HandleFunc("/contact", contact)
http.HandleFunc("/", homepage)
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatalln(err)
}
My first question is: What is this called? I call it mapping URLs to functions, but my Google results haven't been fruitful with those search terms. Is this called "routing"?
Secondly, my goal is to write a small blog app. I want to use a database to save blog posts and other data. However, mapping URLs to functions like I did above doesn't seem right because there is no way to know what the URL should be until someone makes a blog post. I would want the URL to match the blog post title. In addition, there could be hundreds of blog posts, so writing a bunch of http.HandleFunc
s seems unreasonable.
Finally, my question is this: What options are available to solve this obstacle?
答案1
得分: 0
一个“博客应用”的另一种方法是使用静态网站生成器。你可以在gohugo(GitHub仓库)中找到一个很好的例子,这意味着你只有一个处理程序:
if port > 0 {
if !viper.GetBool("DisableLiveReload") {
livereload.Initialize()
http.HandleFunc("/livereload.js", livereload.ServeJS)
http.HandleFunc("/livereload", livereload.Handler)
}
go serve(port)
}
但更一般地说,它被称为路由器,你可以在这个出色的**Go语言第三方路由器指南 2014/11/20**中找到它们:
英文:
The other approach for a "blog app" is a static site generator.
You can find a good example in gohugo (repo GitHub), which means you only have one Handler:
if port > 0 {
if !viper.GetBool("DisableLiveReload") {
livereload.Initialize()
http.HandleFunc("/livereload.js", livereload.ServeJS)
http.HandleFunc("/livereload", livereload.Handler)
}
go serve(port)
}
But more generally, what it is called is a router, and you can see them in this excellent Guide to 3rd Party Routers in Go 2014/11/20:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论