My intention is to create an API as generic and DRY as possible using Go. To achieve this, I have made some more less common decisions:
- To use AJAX call to avoid reloading the entire page (causing flickering) when updating the web page. Instead of using Go.
- To exclude hard coded queries from the API to reduce the endpoints (routes). As a bonus the queries can be modified and added without recompile the API when updating queries
- To use JSON to create and update data to get it more generic.
- To use the sqlx driver in order to further reduce code and avoid repeating.
package main
import (
//"fmt"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
"net/http"
"os"
"strings"
)
var db *sqlx.DB
func main() {
Connect()
http.HandleFunc("/", handler)
http.Handle("/favicon.ico", http.NotFoundHandler())
http.ListenAndServe(":9998", nil)
}
func handler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT,CREATE,DELETE")
w.Header().Set("Access-Control-Allow-Headers", "*")
w.Header().Set("Content-Type", "application/json")
switch r.Method {
case "DELETE":
Delete(w, r)
case "POST":
Create(w, r)
case "PUT":
Update(w, r)
default: //GET
Get(w, r)
}
}
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 = ""
}
return query
}
func getpath(r *http.Request) (string, string, string) {
path := strings.Split(r.URL.String(), "/")
switch len(path) {
case 4:
return path[1], path[2], path[3]
case 3:
return path[1], path[2], ""
case 2:
return path[1], "", ""
default:
return "", "", ""
}
}
My questions are:
- Can you see any security issues? (Except CORS)
- Anything you should done different?
- Any thoughts about the generic approach?
More detailed description is here: Go REST API