Creating your first HTTP PUT method
Whenever we want to update a record that we have created earlier or want to create a new record if it does not exist, often termed an Upsert, then we go with the HTTP PUT
method implementation, which we will cover 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-put.go
where we will define an additional route that supports the HTTPPUT
method and a handler that either updates the employee details for the provided ID or adds an employee to the initial static array of employees; if the ID does not exist, marshal it to the JSON, and write it 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 []Route var routes...