课程: Practice It: Go REST API Server
Using a router
- [Narrator] With an API, which stands for Application Programming Interface, we want to be able to handle the different REST methods which include get post, put, patch, and delete. The way our application is currently set up, we send back "Hello world," regardless if it is a get or a post or delete, or one of the other two. Say we want to have different API methods handled by different GO methods. In other words, we want different request handlers for products and for orders. To accomplish this, we would use a router. A router keeps track of what code to execute based on the API endpoint and method called. I like to use routers for better code layout, as I can group together API handlers based on the resource they affect. We use the line "http.handlefunc" previously, which indicated that any call to our endpoint would be handled by returning "Hello world." But what if I want to answer differently depending on the API method used? To that end, we'll use a router. We added the gorilla/ mux router in the first video, and now we'll use it. First, we'll add "github.com/gorilla/mux" to the import statement. Next, we will instantiate the router. Then we add the same route, but have a different message return for post, get and delete. I've already created the handler functions, so then we'll just add them to the handlers. I've already created the handler functions, so now we'll use them. So, next we'll add the router.HandleFunc. We'll use the main endpoint, and then add the handler that we'll use, which will be getRequest, And then we want to specify by the method used, so this would be methods. And then we will add "GET." Bear in mind that you can add more than one method. You could add post also or delete if you'd like. Then we have, again, the main endpoint. This time it'll be for post. And lastly we'll add one for delete. Now we add the http.Handle, again, the main endpoint and this time we're letting it know to use the router. Then we'll add the log line, and then we'll start the server. Now, in the terminal, I'll start the server. And then in another terminal, I'll make some calls. So, first up will be Curl localhost. If no method is sent, it defaults to GET. So we do the curl and we get this is a GET. Now, we'll try with a post, and for a post we'll add, we can add -X POST. We hit return, and we get this is a POST. And, lastly, we're going to try delete. You could also, instead of the -X, you could just use --request DELETE, and you get "This is DELETE." So you can see how we can have one endpoint but different treatments for that endpoint using a router.