Namespace

namespace is a logical means of organizing the API provided by Beego. Most of the time, when we register routes, we organize them according to certain rules, so using namespace will make the code more concise and maintainable.

For example, our whole application is divided into two blocks, one for the API provided by Android and one for the API provided by IOS. then overall, it can be divided into two namespaces; some applications will have the concept of version, for example, V1 in the early days, V2 was introduced later, and then V3 was introduced later, then the whole application will have three namespaces. Different versions of APIs are registered under different namespaces.

namespace is slightly more complicated, so you may need to write a few more simple demos to master its usage.

Examples

  1. func main() {
  2. uc := &UserController{}
  3. // create namespace
  4. ns := web.NewNamespace("/v1",
  5. web.NSCtrlGet("/home", (*MainController).Home),
  6. web.NSRouter("/user", uc),
  7. web.NSGet("/health", Health),
  8. )
  9. // register namespace
  10. web.AddNamespace(ns)
  11. web.Run()
  12. }
  13. type MainController struct {
  14. web.Controller
  15. }
  16. func (mc *MainController) Home() {
  17. mc.Ctx.WriteString("this is home")
  18. }
  19. type UserController struct {
  20. web.Controller
  21. }
  22. func (uc *UserController) Get() {
  23. uc.Ctx.WriteString("get user")
  24. }
  25. func Health(ctx *context.Context) {
  26. ctx.WriteString("health")
  27. }

You can accessing these URLs:

  • GET http://localhost:8080/v1/home
  • GET http://localhost:8080/v1/user
  • GET http://localhost:8080/v1/health

The rule for these addresses can be summarized as concat. For example, in this example our namespace is prefixed with v1, so it is a v1 segment before the registered route.

Notice that inside the main function, we use a different way to register routes. It can be said that either functional route registration or controller route registration is OK for namespace.

Nested Namespace

Sometimes we want namespace to be nested inside namespace. In this case we can use the web.NSNamespace method to inject a child namespace.

Example:

  1. func main() {
  2. uc := &UserController{}
  3. // initiate namespace
  4. ns := web.NewNamespace("/v1",
  5. web.NSCtrlGet("/home", (*MainController).Home),
  6. web.NSRouter("/user", uc),
  7. web.NSGet("/health", Health),
  8. // 嵌套 namespace
  9. web.NSNamespace("/admin",
  10. web.NSRouter("/user", uc),
  11. ),
  12. )
  13. // register namespace
  14. web.AddNamespace(ns)
  15. web.Run()
  16. }

Start the service, and access GET http://localhost:8080/v1/admin/user, you can see the output.

Conditional Namespace Routes

Beego’s namespace provides a conditional judgment mechanism. Routes registered under the namespace will be executed only if the conditions are met. Essentially, this is just a filter application.

For example, we want the user’s request to have an x-trace-id in the header of the request in order to be processed by subsequent requests:

  1. func main() {
  2. uc := &UserController{}
  3. // 初始化 namespace
  4. ns := web.NewNamespace("/v1",
  5. web.NSCond(func(b *context.Context) bool {
  6. return b.Request.Header["x-trace-id"][0] != ""
  7. }),
  8. web.NSCtrlGet("/home", (*MainController).Home),
  9. web.NSRouter("/user", uc),
  10. web.NSGet("/health", Health),
  11. // 嵌套 namespace
  12. web.NSNamespace("/admin",
  13. web.NSRouter("/user", uc),
  14. ),
  15. )
  16. //注册 namespace
  17. web.AddNamespace(ns)
  18. web.Run()
  19. }

In general, we don’t recommend using this feature now either, because its functionality overlaps with filter. We recommend that you should consider implementing a filter normally yourself if you need to, the code will be more understandable. This feature will be considered to be replaced by a filter in a future version, and the method will be removed later.

Filter

namespace also supports filter. The filter will only work on routes registered under this namespace, and will have no effect on other routes.

We have two ways to add Filter, one is in NewNamespace, calling web.NSBefore or web.NSAfter, or we can call ns.Filter()

  1. func main() {
  2. uc := &UserController{}
  3. // initiate namespace
  4. ns := web.NewNamespace("/v1",
  5. web.NSCond(func(b *context.Context) bool {
  6. return b.Request.Header["x-trace-id"][0] != ""
  7. }),
  8. web.NSBefore(func(ctx *context.Context) {
  9. fmt.Println("before filter")
  10. }),
  11. web.NSAfter(func(ctx *context.Context) {
  12. fmt.Println("after filter")
  13. }),
  14. web.NSCtrlGet("/home", (*MainController).Home),
  15. web.NSRouter("/user", uc),
  16. web.NSGet("/health", Health),
  17. // nested namespace
  18. web.NSNamespace("/admin",
  19. web.NSRouter("/user", uc),
  20. ),
  21. )
  22. ns.Filter("before", func(ctx *context.Context) {
  23. fmt.Println("this is filter for health")
  24. })
  25. // register namespace
  26. web.AddNamespace(ns)
  27. web.Run()
  28. }

Currently, namespace has limited support for filter, only before and after.

More details refer to Filter

NSInclude

Next we discuss something a bit strange, the web.NSInclude method. This method is a companion method to annotate/commente routes companion method.

It only works for annotate/comment routes.

Example:

  1. func init() {
  2. api := web.NewNamespace("/api/v1",
  3. web.NSNamespace("/goods",
  4. web.NSInclude(
  5. &controllers.GoodsController{},
  6. ),
  7. ),
  8. )
  9. web.AddNamespace(api)
  10. }

Notice that our GoodsController here is necessarily a Controller that annotates routes and has been generated using the bee command to generate the annotated routes.

Reference

functional style controller style filter annotate/comment routes