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:

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

报告相同问题?

悬赏问题

  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?