URL’s and routes are defined in the conf/routes file and have three columns as example below:

  1. [METHOD] [URL Pattern] [Controller.Method]
  2. GET / MySite.Welcome

conf example

  1. # Higher priority routes first
  2. module:jobs # Importing jobs includes all the routes from the module
  3. ## main routes
  4. GET / App.Home # A simple path
  5. GET /contact App.Contact # contact page
  6. #GET /contact/ App.Contact # unnecessary as (optional trailing slash is above)
  7. GET /login App.Login
  8. GET /hotels/ Hotels.Index # Match /hotels and /hotels/
  9. GET /hotels/:id Hotels.Show # Extract a URI argument
  10. WS /hotels/:id/feed Hotels.Feed # WebSockets.
  11. POST /hotels/:id/:method Hotels.:method # Automatically route some methods.
  12. PURGE /purge/:key Cache.Purge # Cache
  13. # WebDAV extends the set of standard HTTP verbs and headers allowed for request methods.
  14. PROPFIND /webdav/:key WebDav.PropFind # WebDav
  15. PROPPATCH /webdav/:key WebDav.PropPatch # WebDav
  16. MKCOL /webdav/:key WebDav.MkCol # WebDav
  17. COPY /webdav/:key WebDav.Copy # WebDav
  18. MOVE /webdav/:key WebDav.Mode # WebDav
  19. LOCK /webdav/:key WebDav.Lock # WebDav
  20. UNLOCK /webdav/:key WebDav.UnLock # WebDav
  21. ## Static files. Map /app/public resources under /public/...
  22. GET /public/*filepath Static.Serve("public")
  23. ## Developer Stuff
  24. # Prefix all routes in the testrunner module with /debug/
  25. * /debug/ module:testrunner
  26. ## Finally
  27. # Catch all and Automatic URL generation
  28. * /:controller/:method :controller.:method

Let’s go through the lines one at a time and by the end, we’ll see how toaccomplish reverse routing i.e generating the URL to invoke a particular action.

A Fixed Path

  1. GET /login App.Login
  2. GET /about App.About

The routes above use an ‘exact match’ of HTTP method and path and invoke the Login and Aboutmethod on the App controller.

Trailing slashes/

  1. GET /hotels/ Hotels.Index
  • This route invokes Hotels.Index for both /hotels and /hotels/
  • The reverse route to Hotels.Index will include the trailing slash/
    Trailing slashes should not be used to differentiate between actions. Thesimple path /login will be matched by a request to /login/.

URL :parameters

  1. GET /hotels/:id Hotels.Show
  • Segments of the path may be matched and extracted with a : prefix.
  • The :id variable above will match anything except a slash. For example, /hotels/123 and/hotels/abc would both be matched by the route above.
  • Extracted parameters are available in both the
  1. func(cHotels)Show(idint)revel.Result{...}

or

  1. func(cHotels)Show()revel.Result{varidstring=c.Params.Get("id")...}

or

  1. func(cHotels)Show()revel.Result{varidintc.Params.Bind(&id,"id")...}

Star *parameters

  1. GET /public/*filepath Static.Serve("public")

The starred parameter must bethe first element in the path, and match all remaining path elements.

For example, in the case above it will match any path beginning with /public/, andits value will be the path substring that follows the * prefix.

Fixed Parameters

As also demonstrated in Static Serving below, routes may specify one or moreparameters to the method. For example:

  1. GET /products/:id ShowList("PRODUCT")
  2. GET /menus/:id ShowList("MENU")

The provided argument(s) are bound to a parameter name using their position. Inthis case, the list type string would be bound to the name of the first methodparameter.

This is helpful in situations where:

  • you have a couple similar methods
  • you have methods that do the same thing, but operate in different modes
  • you have methods that do the same thing, but operate on different data types

    Auto Routing

  1. POST /hotels/:id/:method Hotels.:method
  2. * /:controller/:method :controller.:method

URL argument extraction can also be used to determine the invoked method.Matching to controllers and methods is case insensitive.

The first example route line would effect the following routes:

  1. /hotels/1/show => Hotels.Show
  2. /hotels/2/details => Hotels.Details

Similarly, the second example may be used to access any action (Controller.Method) in theapplication:

  1. /app/login => App.Login
  2. /users/list => Users.List

Since matching to controllers and methods are case insensitive, the followingroutes would also work:

  1. /APP/LOGIN => App.Login
  2. /Users/List => Users.List

Using auto-routing as a catch-all (e.g. last route in the file) is useful forquickly hooking up actions to non-vanity URLs, especially in conjunction withthe reverse router.

It is recommended that auto-routing be used for rapid development work, then routes should be fully qualified to avoid exposing a method in a controller

Static Serving

  1. GET /public/*filepath Static.Serve("public")
  2. GET /favicon.ico Static.Serve("public","img/favicon.png")
  3. GET /img/icon.png Static.Serve("public", "img/icon.png") << space causes error

For serving directories of static assets, Revel provides the static built in module,which contains a singleStaticcontroller. Static.Serve method takes two parameters:

  • prefix (string) - A (relative or absolute) path to the asset root.
  • filepath (string) - A relative path that specifies the requested file.
    Important:For the two parameters version of Static.Serve, blank spaces are not allowed between" and , due to how encoding/csv works.

Static content can only be served from within the application root for security reasons. To include external assets consider symbolic links or a git submodule

Modules

Modules which contain routes can be imported into your application in two ways:

In the example below, it’s assumed mymodule has a routes file containing:

  1. GET /gopher MyModule.FetchGopher
  2. POST /gopher/add MyModule.AddGopher

1) Importing routes as-is

  1. # mymodule routes
  2. module:mymodule
  3. # Other routes
  4. GET / Application.Index
  5. GET /bar Application.Bar
  • The routes would be ‘imported’ into your application with the URL’s /gopher and /gopher/add

    2) Importing the routes under a prefixed path

  1. # mymodule routes with prefix - Must be defined with an asterisk * for the method
  2. * /myurl module:mymodule
  3. # Other routes
  4. GET / Application.MyMethod
  5. GET /foo Application.FooMethod
  • The routes would be imported with the URL’s /myurl/gopher and /myurl/gopher/add.
  • See also Modules and Jobs

    Websockets

  1. WS /hotels/:id/feed Hotels.Feed

Websockets are routed the same way as other requests with the ‘method’identifier of WS.

Purge

  1. PURGE /purge/:key Cache.Purge # Cache
  • Purge method is routed the same way as other requests with the method
  • An HTTP purge is similar to an HTTP GET request, except that the method is PURGE.
  • Actually you can call the method whatever you’d like, but most people refer to this as purging.

    WebDav

  1. PROPFIND /webdav/:key WebDav.PropFind # WebDav
  2. PROPPATCH /webdav/:key WebDav.PropPatch # WebDav
  3. MKCOL /webdav/:key WebDav.MkCol # WebDav
  4. COPY /webdav/:key WebDav.Copy # WebDav
  5. MOVE /webdav/:key WebDav.Mode # WebDav
  6. LOCK /webdav/:key WebDav.Lock # WebDav
  7. UNLOCK /webdav/:key WebDav.UnLock # WebDav
  • WebDav Methods are routed the same way as other requests with the method.
  • See the WebDav Documentation for more details.

    Reverse Routing

It is good practice to use a reverse router to generate URL’s instead of hardcoding for a few reasons including:

  • Avoids misspellings
  • The compiler ensures that reverse routes have the right number and type of parameters.
  • Localizes URL changes to one place in the ‘conf/routes’ file.
    Upon building your application, Revel generates an app/routes package. Use itwith a statement of the form:
  1. routes.Controller.Method(param1,param2)

The above statement returns an URL string to Controller.Method with thegiven parameters.

Limitation: Only primitiveparameters to a route are typed due to the possibility of circular imports.Non-primitive parameters are typed as interface{}.

Below is a more complete example:

  1. import("github.com/revel/revel""project/app/routes")typeAppstruct{*revel.Controller}// Show a formfunc(cApp)ViewForm(usernamestring)revel.Result{returnc.Render(username)}// Process the submitted form.func(cApp)ProcessForm(username,inputstring)revel.Result{...ifc.Validation.HasErrors(){c.Validation.Keep()c.Flash.Error("Form invalid. Try again.")returnc.Redirect(routes.App.ViewForm(username))// <--- REVERSE ROUTE}c.Flash.Success("Form processed!")returnc.Redirect(routes.App.ViewConfirmation(username,input))// <--- REVERSE ROUTE}
GoDoc Reference
GitHub Labels

原文: https://revel.github.io/manual/routing.html