How it works…

Once we run the program, the HTTP server will start locally listening on port 8080.

Next, executing a GET request with the path prefix as /v1 from the command line as follows, will give you a list of one set of employees:

$ curl -X GET http://localhost:8080/v1/employees
[{"id":"1","firstName":"Foo","lastName":"Bar"},{"id":"2","firstName":"Baz","lastName":"Qux"}]

 Here, executing a GET request with path prefix as /v2 will give you a list of another set of employees, as follows:

$ curl -X GET http://localhost:8080/v2/employees
[{"id":"1","firstName":"Baz","lastName":"Qux"},{"id":"2","firstName":"Quux","lastName":"Quuz"}]

Sometimes, while designing the REST URL, we prefer to return the default data if the client queries the endpoint without specifying the version in the URL path. To incorporate it, we have modified the getEmployees handler to check for the prefix in the URL and act accordingly. So, executing a GET request without the path prefix from the command line as follows, will give you a list with a single record, which we can call the default or initial response of the REST endpoint called:

$ curl -X GET http://localhost:8080/employees
[{"id":"1","firstName":"Foo","lastName":"Bar"}]

Let’s understand the change we introduced in this recipe: 

  1. First, we defined a single route with the name getEmployees, which executes a getEmployees handler for every GET request for the URL pattern /employees.
  2. Then, we created three arrays, namely employees, employeesV1, and employeesV2, which are returned as a response to an HTTP GET call for the URL patterns /employees, /v1/employees, and /v2/employees respectively.
  3. Next, we have defined a getEmployees handler where we check for the prefix in the URL path and perform an action based on it.
  4. Then, we defined an AddRoutes helper function, which iterates over the routes array we defined, adds it to the gorilla/mux router, and returns the Router object.
  5. Finally, we defined main() where we create a gorilla/mux router instance using the NewRouter() handler with the trailing slash behavior for new routes as true, and add routes to it calling the AddRoutes helper function passing the default router and two subrouters, one with the prefix as v1 and the other with the prefix as v2.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.78.136