Defining REST APIs and routes
While writing RESTful APIs, it's very common to authenticate the user before allowing them to access it. A prerequisite to authenticating the user is to create the API routes, which we will be covering in this recipe.
How to do it…
- Install the
github.com/gorilla/mux
andgithub.com/gorilla/handlers
packages using thego get
command, as follows:
$ go get github.com/gorilla/mux $ go get github.com/gorilla/handlers
- Create
http-rest-api.go
, where we will define three routes—/status
,/get-token
and/employees
—along with their handlers, as follows:
package main import ( "encoding/json" "log" "net/http" "os" "github.com/gorilla/handlers" "github.com/gorilla/mux" ) const ( CONN_HOST = "localhost" CONN_PORT = "8080" ) type Employee struct { Id int `json:"id"` FirstName string `json:"firstName"` LastName string `json:"lastName"` } type Employees []Employee var employees []Employee func init() { employees = Employees { Employee{Id: 1, FirstName...