Delete

DELETE (DELETE/DELETE)

DELETE

The DELETE part of REST API is rather simple. DELETE one row with ID = ?. Done.

2. Do an AJAX Request with retuning data

The AJAX Request accepts dynamic call (+path) and writes back to the HTML page target (id="data")

function api3get(path) {
var url = "https://api3.go4webdev.org/"+path;
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.setRequestHeader("Accept", "application/json");
xhr.onload = function() {
if (xhr.readyState === 4) {
document.getElementById("data").innerHTML = this.responseText
}
};
xhr.send();
}
3+4. Lookup and get SQL Query from the REST call

Instead of storing each Query in the API, the query is stored in a database (almost similar to the Postgresql view function) fetched for each request. This means easier to maintain and more generic API (fewer endpoints)

The query is fetced with an id "tsk_all" from the REST call https://api3.go4webdev.org/tsk/all

func Getquery(path string) string {
// get query from lookup db
var query string
err := db.QueryRow("SELECT sql_query FROM sqls WHERE sql_id=$1", path).Scan(&query)
if err != nil {
path = ""
}
fmt.Println(query)
return query
}

The lookup Query look like this with a parameter $1.

DELETE FROM tsk WHERE tsk_id = $1
5+6. Execute the SQL Query

The DELETE endpoint in the Go API does not return any data.

package main

import (
"net/http"
)

func Delete(w http.ResponseWriter, r *http.Request) {
scope, action, val := getpath(r)
switch action {
case "del":
query := Getquery(scope + "_" + action)
delete(query, val)
}
}

// delete record
func delete(query string, val string) {
db.MustExec(query, val)
}

All steps above put together: