doubianyan9749 2017-05-19 17:19
浏览 23
已采纳

随着项目变大,如何在go中组织处理程序?

I am building a website with Go and I know how it works and how to handle routes with handlefunc(). however, my website is getting bigger and I will probably have alot of urls. the question is how to handle all this ? I cannot just add for example 100+ or 500+ handelfunc() in my main() to match each possible route or url for example. so how to manage it ? thanks in advance.

NOTE ::

my question doesn't require any code.

  • 写回答

1条回答 默认 最新

  • dsjk3214 2017-05-19 17:37
    关注

    You definitely should not put 500+ HandleFunc in your main.

    To begin with, as the project goes bigger you'll probably create modules and types.

    You can then delegate to these modules or types from your main so that then each module or type would then register handles themselves.

    Also, probably many of your URLs will follow patterns, such as:

    "/articles/{id}"
    

    If that's the case, you should just register that pattern once, and then the function handling the request can operate based on the parameter {id}.

    There are several libraries out there that can help manage the routing if using patterns, or you can also code your own routing logic.

    Take a look at this question for some alternatives on that matter:

    Wildcards in the pattern for http.HandleFunc

    For example, if you where using Chi (https://github.com/pressly/chi) to manage the routing, in your main you can do:

    r := chi.NewRouter()
    r.Mount("/admin", adminRouter())
    

    And then inside that adminRouter() function you keep creating handlers that will be served under /admin:

    func adminRouter() http.Handler {
        r := chi.NewRouter()
        r.Use(AdminOnly)
        r.Get("/", adminIndex)
        r.Get("/accounts", adminListAccounts)
        return r
    }
    

    (all this is taken from Chi's documentation)

    This is just an example, you can implement similar logic using a different way.

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

报告相同问题?

悬赏问题

  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考