[beego] routing settings of beego

beego has three routes: fixed route, regular route and automatic route

 

Basic routing

Since beego version 1.2, it supports basic RESTful functional routing. Most routes in applications will be defined in {routes / router Go file. The simplest beego route consists of a URI and a closure function.

Basic GET route

beego.Get("/",func(ctx *context.Context){
     ctx.Output.Body([]byte("hello world"))
})

Basic POST routing

beego.Post("/alice",func(ctx *context.Context){
     ctx.Output.Body([]byte("bob"))
})

Register a route that can respond to any HTTP

beego.Any("/foo",func(ctx *context.Context){
     ctx.Output.Body([]byte("bar"))
})
 

All supported basic functions are as follows

  • beego.Get(router, beego.FilterFunc)
  • beego.Post(router, beego.FilterFunc)
  • beego.Put(router, beego.FilterFunc)
  • beego.Patch(router, beego.FilterFunc)
  • beego.Head(router, beego.FilterFunc)
  • beego.Options(router, beego.FilterFunc)
  • beego.Delete(router, beego.FilterFunc)
  • beego.Any(router, beego.FilterFunc)
 

Support custom handler implementation

Sometimes we have implemented some rpc applications, but we want to integrate them into beego, or other HTTP server applications into beego Now you can easily integrate:

 
s := rpc.NewServer()
s.RegisterCodec(json.NewCodec(), "application/json")
s.RegisterService(new(HelloService), "")
beego.Handler("/rpc", s)

beego. The handler (router, http.Handler) function is the key. The first parameter represents the routing URI, and the second is the HTTP Handler, which will distribute all requests prefixed with rpc to http Handler

In fact, the third parameter of this function is whether it is prefix matching. The default is false. If true is set, the prefix will be matched when the route is matched, that is, / rpc/user , will also be matched to run

Routing parameters

Fixed routing and regular routing will be discussed later. These parameters are also applicable to the above functions

 

RESTful Controller routing

Before introducing the routing implementation of these three beego, first introduce RESTful. We know that RESTful is a form widely used in API development. By default, beego supports such request methods, that is, users execute the Get method when they Get a request and the Post method when they Post a request. Therefore, the default route is such a RESTful request mode.

 

Fixed route

Fixed routes are fully matched routes, as shown below:

beego.Router("/", &controllers.MainController{})
beego.Router("/admin", &admin.UserController{})
beego.Router("/admin/index", &admin.ArticleController{})
beego.Router("/admin/addpkg", &admin.AddController{})

The route shown above is our most commonly used route, a fixed route, a controller, and then request the corresponding methods in the controller according to different user request methods, a typical RESTful way.

 

Regular routing

In order to make routing settings more convenient for users, beego refers to the routing implementation of sinatra and supports multiple routes:

  • beego.Router("/api/?:id", &controllers.RController{})

    Default matching / / for example, "URL" / api/123 "can be matched successfully. At this time, the value of" id "is" 123 "

  • beego.Router("/api/:id", &controllers.RController{})

    Default matching / / for example, "URL" / api/123 "can be matched successfully. At this time, the value of" id "is" 123 ", but the matching of" URL "/ api /" fails

  • beego.Router("/api/:id([0-9]+)", &controllers.RController{})

    User defined regular matching / / for example, "URL" / api/123 "can be matched successfully. At this time, the value of" id "is" 123 "

  • beego.Router("/user/:username([\\w]+)", &controllers.RController{})

    Regular string matching / / for example, "URL" / user/astaxie "can be matched successfully. At this time, the value of" username "is" astaxie "

  • beego.Router("/download/*.*", &controllers.RController{})

    *Matching method / / for example, for URL "/ download / file/api xml "can be matched successfully. At this time, the value of variable": path "is" file/api "and the value of": ext "is" xml "

  • beego.Router("/download/ceshi/*", &controllers.RController{})

    *Full matching method / / for example, for URL "/ download / ceshi / file / API JSON "can be matched successfully. At this time, the value of" splat "is" file / API " json”

  • beego.Router("/:id:int", &controllers.RController{})

    Int type setting method, matching: the id is int type, and the framework helps you realize regular ([0-9] +)

  • beego.Router("/:hi:string", &controllers.RController{})

    String type setting method, matching: hi is string type. Framework helps you realize regular ([\ w] +)

  • beego.Router("/cms_:id([0-9]+).html", &controllers.CmsController{})

    Custom regular with prefix / / matching: ID is regular type. Matching cms_123.html URL: id = 123

The above variables can be obtained in the Controller in the following ways:

this.Ctx.Input.Param(":id")
this.Ctx.Input.Param(":username")
this.Ctx.Input.Param(":splat")
this.Ctx.Input.Param(":path")
this.Ctx.Input.Param(":ext")

Custom methods and RESTful rules

The above list is the default request method name (the request method is consistent with the function name, for example, the get request executes the get function, and the post request executes the post function). If you want to customize the function name, you can use the following method:

beego.Router("/",&IndexController{},"*:Index")

The third parameter is used to set the corresponding method to the function name, which is defined as follows

  • *Indicates that any method executes the function
  • Use httpmethod:funcname format to display
  • Multiple different formats are used; Split
  • Multiple method s correspond to the same funcname. Methods are separated by

The following is an example of a RESTful design:

beego.Router("/api/list",&RestController{},"*:ListFood")
beego.Router("/api/create",&RestController{},"post:CreateFood")
beego.Router("/api/update",&RestController{},"put:UpdateFood")
beego.Router("/api/delete",&RestController{},"delete:DeleteFood")

The following is an example of multiple HTTP methods pointing to the same function:

beego.Router("/api",&RestController{},"get,post:ApiFunc")

The following are different method s corresponding to different functions; Examples of segmentation:

beego.Router("/simple",&SimpleController{},"get:GetFunc;post:PostFunc")

Available HTTP methods:

  • *: contains all of the following functions:
  • get: GET request
  • post: POST request
  • put: PUT request
  • delete: DELETE request
  • patch: PATCH request
  • options: OPTIONS request
  • head: HEAD request

If * and the corresponding HTTP Method exist at the same time, the method of HTTP Method will be implemented first. For example, the following routes are registered at the same time:

beego.Router("/simple",&SimpleController{},"*:AllFunc;post:PostFunc")

When executing a POST request, execute PostFunc instead of AllFunc.

The routing of custom functions does not support RESTful methods by default, that is, if you set {beego For routes such as router ("/ API", & restcontroller {}, "post: apifunc"), if the requested method is "post", the "post" function will not be executed by default.

 

Automatic matching

First, the user needs to register the controller to be routed into automatic routing:

beego.AutoRouter(&controllers.ObjectController{})

Then beego will get all the implementation methods in the structure through reflection, and you can access the corresponding methods in the following ways:

/object/login   call ObjectController Medium Login method
/object/logout  call ObjectController Medium Logout method

In addition to the matching of the two prefixes /: controller/:method , the remaining url beego will help you automatically parse it into parameters and save it in , this Ctx. Input. Params:

/object/blog/2013/09/12  call ObjectController Medium Blog Method, the parameters are as follows: map[0:2013 1:09 2:12]

The method name internally stores the user settings, such as Login. When the url matches, it will be converted to lowercase. Therefore, URLs such as / object/LOGIN can also be routed to the user-defined Login method.

Now it is possible to automatically identify all URLs similar to the following and distribute the request to the simple method of the controller:

/controller/simple
/controller/simple.html
/controller/simple.json
/controller/simple.xml

You can use this Ctx. Input. Param (": ext") gets the suffix.

Annotation routing

Since beego version 1.3, annotation routing has been supported. Users do not need to register routes in the router. They only need to Include the corresponding controller, and then write the router annotation (/ / @ router) on the method method method of the controller. For detailed use, please see the following example:

// CMS API
type CMSController struct {
    beego.Controller
}

func (c *CMSController) URLMapping() {
    c.Mapping("StaticBlock", c.StaticBlock)
    c.Mapping("AllBlock", c.AllBlock)
}


// @router /staticblock/:key [get]
func (this *CMSController) StaticBlock() {

}

// @router /all/:key [get]
func (this *CMSController) AllBlock() {

}

It can be found in the router The route registration method is as follows:

beego.Include(&CMSController{})

beego will automatically analyze the source code. Note that it will only be generated in dev mode. The generated routes are placed in the "/ routes / commentsrouter. Go" file.

In this way, the above route supports the following routes:

  • GET /staticblock/:key
  • GET /all/:key

In fact, the effect is the same as registering through the Router function:

beego.Router("/staticblock/:key", &CMSController{}, "get:StaticBlock")
beego.Router("/all/:key", &CMSController{}, "get:AllBlock")

At the same time, we have noticed that the URLMapping function is added in the new version. This is a newly added function. If the user does not register, the corresponding function will be executed through reflection. If registered, the function will be executed through the interface, and the performance will be improved a lot.

namespace

//Initialize namespace
ns :=
beego.NewNamespace("/v1",
    beego.NSCond(func(ctx *context.Context) bool {
        if ctx.Input.Domain() == "api.beego.me" {
            return true
        }
        return false
    }),
    beego.NSBefore(auth),
    beego.NSGet("/notallowed", func(ctx *context.Context) {
        ctx.Output.Body([]byte("notAllowed"))
    }),
    beego.NSRouter("/version", &AdminController{}, "get:ShowAPIVersion"),
    beego.NSRouter("/changepassword", &UserController{}),
    beego.NSNamespace("/shop",
        beego.NSBefore(sentry),
        beego.NSGet("/:id", func(ctx *context.Context) {
            ctx.Output.Body([]byte("notAllowed"))
        }),
    ),
    beego.NSNamespace("/cms",
        beego.NSInclude(
            &controllers.MainController{},
            &controllers.CMSController{},
            &controllers.BlockController{},
        ),
    ),
)
//Register namespace
beego.AddNamespace(ns)

The above code supports the following request URL

  • GET /v1/notallowed
  • GET /v1/version
  • GET /v1/changepassword
  • POST /v1/changepassword
  • GET /v1/shop/123
  • GET /v1/cms / corresponds to annotation routes in MainController, CMSController and BlockController

It also supports pre filtering, conditional judgment and infinite nested namespace

The interface of namespace is as follows:

  • NewNamespace(prefix string, funcs ...interface{})

    Initialize the namespace object. The following functions are the methods of the namespace object, but it is strongly recommended to use the corresponding function starting with NS for registration, because it is easier to see the level relationship of the route through gofmt tool

  • NSCond(cond namespaceCond)

    The namespace can be executed if the conditions are met, and not if the conditions are not met

  • NSBefore(filiterList ...FilterFunc)

  • NSAfter(filiterList ...FilterFunc)

    The above corresponds to beforeRouter and FinishRouter filters respectively. Multiple filters can be registered at the same time

  • NSInclude(cList ...ControllerInterface)

  • NSRouter(rootpath string, c ControllerInterface, mappingMethods ...string)

  • NSGet(rootpath string, f FilterFunc)

  • NSPost(rootpath string, f FilterFunc)

  • NSDelete(rootpath string, f FilterFunc)

  • NSPut(rootpath string, f FilterFunc)

  • NSHead(rootpath string, f FilterFunc)

  • NSOptions(rootpath string, f FilterFunc)

  • NSPatch(rootpath string, f FilterFunc)

  • NSAny(rootpath string, f FilterFunc)

  • NSHandler(rootpath string, h http.Handler)

  • NSAutoRouter(c ControllerInterface)

  • NSAutoPrefix(prefix string, c ControllerInterface)

    The above functions are used to set the route. The detailed use is the same as the corresponding function of beego above

  • NSNamespace(prefix string, params ...innnerNamespace)

    Nesting other namespace s

    ns :=
    beego.NewNamespace("/v1",
        beego.NSNamespace("/shop",
            beego.NSGet("/:id", func(ctx *context.Context) {
                ctx.Output.Body([]byte("shopinfo"))
            }),
        ),
        beego.NSNamespace("/order",
            beego.NSGet("/:id", func(ctx *context.Context) {
                ctx.Output.Body([]byte("orderinfo"))
            }),
        ),
        beego.NSNamespace("/crm",
            beego.NSGet("/:id", func(ctx *context.Context) {
                ctx.Output.Body([]byte("crminfo"))
            }),
        ),
    )

The following functions are all methods belonging to * Namespace objects: it is not recommended to use them directly. Of course, the effect is the same as that of the functions starting with NS above, but the above method is more elegant and the written code is easier to understand

  • Cond(cond namespaceCond)

    Support the execution of the namespace if the conditions are met, and not if the conditions are not met. For example, you can control the namespace according to the domain name

  • Filter(action string, filter FilterFunc)

    action indicates where you need to execute, before and after respectively indicate the filter before and after executing the logic

  • Router(rootpath string, c ControllerInterface, mappingMethods ...string)

  • AutoRouter(c ControllerInterface)

  • AutoPrefix(prefix string, c ControllerInterface)

  • Get(rootpath string, f FilterFunc)

  • Post(rootpath string, f FilterFunc)

  • Delete(rootpath string, f FilterFunc)

  • Put(rootpath string, f FilterFunc)

  • Head(rootpath string, f FilterFunc)

  • Options(rootpath string, f FilterFunc)

  • Patch(rootpath string, f FilterFunc)

  • Any(rootpath string, f FilterFunc)

  • Handler(rootpath string, h http.Handler)

    The above functions are used to set the route. The detailed use is the same as the corresponding function of beego above

  • Namespace(ns ...*Namespace)

More example codes:

//APIS
ns :=
    beego.NewNamespace("/api",
        //The formal version here is changed to verify the encryption request
        beego.NSCond(func(ctx *context.Context) bool {
            if ua := ctx.Input.Request.UserAgent(); ua != "" {
                return true
            }
            return false
        }),
        beego.NSNamespace("/ios",
            //Crud create, read, update and delete
            beego.NSNamespace("/create",
                // /api/ios/create/node/
                beego.NSRouter("/node", &apis.CreateNodeHandler{}),
                // /api/ios/create/topic/
                beego.NSRouter("/topic", &apis.CreateTopicHandler{}),
            ),
            beego.NSNamespace("/read",
                beego.NSRouter("/node", &apis.ReadNodeHandler{}),
                beego.NSRouter("/topic", &apis.ReadTopicHandler{}),
            ),
            beego.NSNamespace("/update",
                beego.NSRouter("/node", &apis.UpdateNodeHandler{}),
                beego.NSRouter("/topic", &apis.UpdateTopicHandler{}),
            ),
            beego.NSNamespace("/delete",
                beego.NSRouter("/node", &apis.DeleteNodeHandler{}),
                beego.NSRouter("/topic", &apis.DeleteTopicHandler{}),
            )
        ),
    )

beego.AddNamespace(ns)

Tags: Go

Posted by gusaps on Sat, 14 May 2022 02:59:29 +0300