Page MenuHomeHexavara Tech

Handler
Updated 1,864 Days AgoPublic

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.

  1. GET users
func GetUser(conditions map[string]string) (*sql.Rows, error) {
	q := crema.GetGenericSelectQuery("users", conditions, "id")

	return crema.ExecuteQuery(q.QueryString)
}
  1. POST users
func PostUser(tx *sql.Tx, values map[string]string) *sql.Row {
	q := crema.GetGenericInsertQuery("users", values)

	return crema.ExecuteQueryRow(tx, q.QueryString)
}
  1. 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)
}
  1. 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

Last Author
galang
Last Edited
Oct 15 2019, 3:45 PM

Event Timeline

galang created this object.Oct 15 2019, 2:49 PM
galang edited the content of this document. (Show Details)Oct 15 2019, 3:45 PM