How it works…

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

Next, executing a GET request to the REST client from the command line as follows will give you a list of all the employees from the service: 

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

Similarly, run http-rest-post.go, which we created in one of our previous recipes, in a separate terminal by executing the following command:

$ go run http-rest-post.go

Execute a POST request to the REST client from the command line, as follows:

$ curl -H "Content-Type: application/json" -X POST -d '{"Id":"3", "firstName":"Quux", "lastName":"Corge"}' http://localhost:8090/employee/add
[{"id":"1","firstName":"Foo","lastName":"Bar"},{"id":"2","firstName":"Baz","lastName":"Qux"},{"id":"3","firstName":"Quux","lastName":"Corge"}]

This will add an employee to the initial static list and return an updated list of the employees, which will look as shown in the following screenshot:

Let’s understand the program we have written: 

  1. Using import ("encoding/json" "fmt" "log" "net/http" "github.com/gorilla/mux" resty “gopkg.in/resty.v1"), we imported github.com/gorilla/mux to create a Gorilla Mux Router and gopkg.in/resty.v1 with the package alias as resty, which is a REST client of Go, having various handlers to consume the RESTful web service.
  2. Using const WEB_SERVICE_HOST string = "http://localhost:8080", we declared the complete URL of the RESTful web service host.
Depending on the project size, you can move the WEB_SERVICE_HOST string to the constants file or to the properties file, helping you to override its value at runtime.
  1. Next, we defined a getEmployees handler where we create a new resty request object calling its R() handler, call the Get method, which performs the HTTP GET request, gets the response, and writes it to an HTTP response.
  2. Similarly, we defined three more handlers that do the POST, PUT, and DELETE requests to the RESTful service and a main() where we create a gorilla/mux router instance and register the /employees URL path with the getEmployees handler and /employee/add, /employee/update, and  /employee/delete with the addEmployee, updateEmployee, and deleteEmployee handlers, respectively.
..................Content has been hidden....................

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