douquanzhan0315 2014-11-28 00:48
浏览 9
已采纳

将可变数量的网址映射到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条回答 默认 最新

  • duanchuanqu593743 2014-11-28 06:35
    关注

    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:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?