Handler
Handler
Introduction
Crema uses standard function handler of the type http.HandlerFunc which takes an http.ResponseWriter and an http.Request as its arguments.
For example from this endpoints, we can define a handler
func hello(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello World!")) }
Using Generic Handler
Crema provides us with a generic handlers to create a basic application of CRUD faster. As an example, we'll begin by creating the CRUD endpoints for a resource named users:
server.AddRoutes(http.MethodGet, "/users", crema.MakeGenericGetHandler(GetUser)) server.AddRoutes(http.MethodPost, "/users", crema.MakeGenericPostHandler(PostUser)) server.AddRoutes(http.MethodPut, "/users/{id}", crema.MakeGenericPutHandler(PutUser)) server.AddRoutes(http.MethodDelete, "/users/{id}", crema.MakeGenericDeleteHandler(DeleteUser))
Then we set up the handler corresponding each endpoint.
- GET users
func GetUser(conditions map[string]string) (*sql.Rows, error) { q := crema.GetGenericSelectQuery("users", conditions, "id") return crema.ExecuteQuery(q.QueryString) }
- POST users
func PostUser(tx *sql.Tx, values map[string]string) *sql.Row { q := crema.GetGenericInsertQuery("users", values) return crema.ExecuteQueryRow(tx, q.QueryString) }
- UPDATE users
func PutUser(tx *sql.Tx, values map[string]string) (sql.Result, error) { q := crema.GetGenericUpdateQuery("users", values, "id") return crema.ExecuteNonQuery(q.QueryString) }
- DELETE users
func DeleteUser(tx *sql.Tx, conditions map[string]string) (sql.Result, error) { q := crema.GetGenericDeleteQuery("users", conditions, "id") return crema.ExecuteNonQuery(q.QueryString) }
Explanation
UPDATED SOON
Tags
None
Subscribers
None
- Last Author
- • galang
- Last Edited
- Oct 15 2019, 3:45 PM