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.

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

报告相同问题?