Creating your first HTTP GET method
While writing web applications, we often have to expose our services to the client or to the UI so that they can consume a piece of code running on a different system. Exposing the service can be done with HTTP protocol methods. Out of the many HTTP methods, we will be learning to implement the HTTP GET
method in this recipe.
How to do it…
- Install the
github.com/gorilla/mux
package using thego get
command, as follows:
$ go get github.com/gorilla/mux
- Create
http-rest-get.go
where we will define two routes—/employees
and/employee/{id}
along with their handlers. The former writes the static array of employees and the latter writes employee details for the provided ID to an HTTP response stream, as follows:
package main import ( "encoding/json" "log" "net/http" "github.com/gorilla/mux" ) const ( CONN_HOST = "localhost" CONN_PORT = "8080" ) type Route struct { Name string Method string Pattern string HandlerFunc http.HandlerFunc } type Routes...