将可变数量的URL映射到HandleFunc函数。

huangapple go评论98阅读模式
英文:

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.HandleFuncs seems unreasonable.

Finally, my question is this: What options are available to solve this obstacle?

答案1

得分: 0

一个“博客应用”的另一种方法是使用静态网站生成器。你可以在gohugoGitHub仓库)中找到一个很好的例子,这意味着你只有一个处理程序

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:

huangapple
  • 本文由 发表于 2014年11月28日 08:48:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/27180513.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定